I am new to JavaScript and I am trying to understand what await does and what is its relation with microtask queue. The following code is just for clarification purpose only.
async function afunc() {
console.log("a1");
const b = bfunc();
console.log("a2");
b.then((value) => {
console.log(value);
});
return "a value";
}
async function bfunc() {
console.log("b1");
await console.log("waiting");
console.log("b2");
return "b value";
}
const a = afunc();
a.then((value) => {
console.log(value);
});
console.log("script end");
And the results are:
a1
b1
waiting
a2
script end
b2
a value
b value
On MDN it says
The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.
When does this 'resume' happen exactly? And does it has anything relatable to microtask queue in terms of execution order?
Also, I expect b value to show up before a value since it seems that b.then() will be pushed in microtask queue before a.then() is, and the actual output confused me a lot.
Any help would be much appreciated!
Edit:
If you remove await in bfunc, the result would be like:
a1
b1
waiting
b2
a2
script end
b value
a value
When MDN says resume execution of the async function, it means that it will wait for the function inside to be completed, then continue running the outer function.
For example:
async function outer() {
console.log("outer function start");
await inner();
console.log("outer function end");
}
async function inner() {
console.log("inner function start");
await new Promise(resolve => setTimeout(() => resolve(), 1000));
console.log("inner function end");
}
outer();
Will log:
outer function start
inner function start
* 1 second pause *
inner function end
outer function end
I think the reason you are seeing the logs out of order is because you are running b.then, but there is also code outside of the async callback, so the code afterwards isn't necessarily run in order.
JavaScript promises work because of microtasks, so they are related.
JavaScript promises and the Mutation Observer API both use the microtask queue to run their callbacks. - MDN
I hope this helps!