async function funcTwo() {
return new Promise((r) => r());
}
async function funcOne() {
console.log("A");
(async () => {
await funcTwo();
console.log("B");
})();
console.log("C");
}
await funcOne();
console.log("Done");
According to my knowledge the output should be as follows:
A
C
B
Done
My reasoning is:
1.funcOne
runs
2.A
is printed
3.async function runs and promise is resolved immediately thus console.log("B")
is moved to the mircotask queue
4.C
is printed
5.funcOne is resolved and console.log("Done");
is moved to the mircotask queue.
6.Tasks are fetched from the queue and B
and Done
are printed in that order. (console.log("B")
is added to the queue before console.log("done")
)
However the output is:
A
C
Done
B
B
and Done
are switched
Can someone explain what I got wrong?
2
Answers
This is a tricky exercise that explores concepts like the task queue, microtask queue, and how the event loop works.
When the program runs,
await funcOne
will be called (and placed inside the microtask queue), and it will immediately output "A" because this is a synchronous operation. Next, the IIFE will execute. At theawait funcTwo()
line, funcTwo runs and completes immediately. However, the.then
callback of the promise is not executed right away. Instead, it is placed in the microtask queue.The program will then move on from the IIFE without waiting (because don’t have any await to hold it) for its result to complete and proceed to the next synchronous task, which is logging "C." At this point, the execution of funcOne finishes, and the program continues after
await funcOne();
, logging "Done." because is the next synchronous operation.Once all the synchronous tasks are finished, the event loop will process the microtask queue. This is when "B" will be logged.
In this link, you can have a more detail explanation about those three concepts.
If you have an
async
function that executes areturn
with a promise object, then the promise that the function returns will be pending, never settled. The promise returned by theasync
function will be locked-in to the promise given to thereturn
statement.Let’s give the involved promises some names. This is essentially the same script, but with variable names for all relevant promises:
Even though
p0
is a fulfilled promise,p2
is not.p2
is locked-in top0
, and internally athen
is attached top0
to listen for its fulfillment, so thatp2
can follow that same state transition, and be fulfilled too. But such (hidden)then
callback needs a promise job to be put in the queue (microtask queue). As a consequence,p0
will not fulfill synchronously, but later.On the other hand,
funcOne
returns a fulfilled promise, as there is noawait
it executes itself. Note that theawait
in the nested anonymous function only pauses that anonymous function, notfuncOne
. The latter will continue to log "B" without considering the state of any promise, and so it returnsundefined
as the value of a fulfilled promise.If you make your reasoning with this principle, you’ll see the output you get is the one that is expected.
Here is a simplified view on the sequence of operations. It depicts the callstack at the left, the current action being performed, the state of all relevant promises (F=Fulfilled, P=pending), and the jobs that are in the promise job queue (microtask queue):
f1()
log('A')
f3()
f2()
r()
p0 = resolve(...)
return p0
p2 = ...
fulfill(p2)
await p2
fulfill(p2)
p3 = ...
fulfill(p2)
log('C')
fulfill(p2)
return
fulfill(p2)
p1 = ...
fulfill(p2)
await p1
fulfill(p2)
resume script
fulfill(p2)
resume script
fullfill(p2)
fullfill(p2)
resume script
resume f3
resume script
resume f3
log('D')
resume f3
resume f3
log('B')
return