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