Search code examples
javascriptasynchronousnestjs

Does NestJS guarantee to run async methods after return?


What will happen when a code without await an async function returns from a REST API of NestJS?

// modified from https://stackoverflow.com/questions/59829254
@Post()
async create(@Body() body: Dto, @Headers('id') id: string) {   
  body.id = id;    
  const item = await this.service.create(body);
  this.service.anotherAsyncMethod().then(...).catch(...); 

  return item;
}

In this example, does the process always live to run the complete anotherAsyncMethod? If it does, how can it be? Do NestJS or Javascript itself guarantee the way to execute?

It seems there are some waitings in simple test code.

async function asyncFunction() {
  setTimeout(() => console.log("after 3s"), 3000);
}
asyncFunction();
console.log('END');

// output
// END
// after 3s

But I could not find the clue that it always work in NestJS scenario and the others.


Solution

  • In JavaScript, any piece of code that comes before the return statement will be executed. Do not forget that the await statement will only wait for the result, and if you put await before an async operation, it will wait for its result, but even if you did not put await, the async operation still placed in the event loop and will still be executed.

    The only principle is that all these operations should be before the return statement. The return means termination of that function. Not only in JavaScript but in all languages, nothing will be executed after return.

    function someOperations(status) {
      return new Promise((res, rej) => {
          setTimeout(() => {
            console.log(status)
            res('done');
          }, 3000);
      });
    }
    
    (async () => {
      console.log('start...');
      await someOperations('first');
      someOperations('second');
      console.log('second someOperations skipped for now');
      return;
      console.log('unreachable'); // will not be executed
    })()