Search code examples
javascriptapiasynchronouspromisetimeout

Understanding the order of async calls and setTimeouts


The code below contains a function (logger) that sets a timeout, then consoles an async function, then consoles an element ('c').

The output here is 'a', 'b', 'c'.

How is it that 'c' waits for the other two to return? The await call is inside a console.log, so I thought the 'c' console will go ahead and execute since await isn't at the beginning of the console call for 'b'.

In other words, I thought the output should be 'c','a','b'.

Any enlightenment here would be much appreciated!

async function apiCall() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('b');
    }, 50);
  });
}

async function logger() {
  setTimeout(() => console.log('a'), 10);
  console.log(await apiCall());
  console.log('c');
}

logger();


Solution

  • The await inside the console.log() call represents a point at which the logger() function will return an intermediate promise. Note that the line of code is equivalent to

      let p = await apiCall();
      console.log(p);
    

    The expression parameters in a function call are evaluated before the function is called. Thus, the whole function (logger()) has to wait for the promise to resolve before it can proceed to call console.log().