Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading