1

I am new to Javascript and unable to understand the Async/Await behaviour. I have read that Await is for Promises and should not affect non-promise items. But when I used Await with setTimeout it behaved differently.

async function foo() {
  console.log('FIrst');
  await setTimeout(()=>{console.log('timeout')},1000);
  console.log('Second');
} 
foo();
console.log('Three');
//Output is
//FIrst
//Three
//Second
//timeout

But when I remove await it gives

function foo() {
  console.log('FIrst');
  setTimeout(()=>{console.log('timeout')},1000);
  console.log('Second');
} 
foo();
console.log('Three');
//Output is
//FIrst
//Second
//Three
//timeout

So my question is in first code if it's actually waiting for settimeout to finish then why is it printing Second before timeout. Shouldn't it be timeout then Second

EDIT: Some comments say it is due to microtask Queue but can you explain the flow between callback queue and Microtask Queue.

epascarello
  • 204,599
  • 20
  • 195
  • 236
Tinfinity
  • 84
  • 1
  • 8
  • What output do you want? – Andy Jun 09 '22 at 18:54
  • @Andy If await works for non-promises like it does for promises then I was expecting Output as //FIrst //Three //timeout //Second – Tinfinity Jun 09 '22 at 18:59
  • 2
    "*it's actually waiting for settimeout to finish*" it's not. In that, it won't wait until the callback is triggered. It would "wait for setTimeout to finish" in that the call will resolve, the callback will be registered with a timer. The `await` just adds the rest of the function to the microtask queue, hence why "Three" is printed. – VLAZ Jun 09 '22 at 18:59
  • "*If await works for non-promises like it does for promises*" it doesn't. I don't know where you got that idea but your experiment also directly disproves it. – VLAZ Jun 09 '22 at 18:59
  • const delay = (duration) => new Promise(resolve => setTimeout(resolve, duration)); This method would be a common practice of using await with setTimeout – Guy Jun 09 '22 at 19:06

0 Answers0