0

My understanding is that the promise in await promise expression gets pushed to Microtask Queue, so it would settle after the call stack is empty. The below code works as I expected:

async function func() {
  console.log(await Promise.resolve('bagel'));
}

func();
console.log('synchronous log');

// Result:
// synchronous log
// bagel

But if I await something not a Promise like this, the order of the logs changed:

async function func() {
  await console.log('bagel');
}

func();
console.log('synchronous log');

// Result:
// bagel
// synchronous log

What happens behind-the-scenes when I call await? What is the order of executing when awaiting a non-Promise? And specifically await console.log?

vietan
  • 126
  • 1
  • 7
  • `await console.log(…)` makes no sense, that's the same as `console.log(…); await undefined;`. You probably meant `console.log(await 'bagel')`? – Bergi Apr 02 '23 at 08:48
  • "*My understanding is that the promise gets pushed to Microtask Queue*" - no, the task queue does not contain promises. The *task* (`.then()` handler) that resumes the execution of the `async` function is pushed to the microtask queue when the promise is resolved. – Bergi Apr 02 '23 at 08:50

1 Answers1

2

In your case you have

async function func() {
  let un = console.log('bagel');
  await un;
}

func();
console.log('synchronous log');

So the order is obvious

In case of

async function func() {
  await 0;
  console.log('bagel');
}

func();
console.log('synchronous log');

synchronous one will also be the first, as await pauses function execution

If you want your "syncronous" await to be syncronous you have to not await it if it's not a promise

async function func(wait) {
  if (wait?.then) {
    await wait
  }
}
Dimava
  • 7,654
  • 1
  • 9
  • 24