I am trying to understand what microtask get enqueued when a Promise is resolved with another Promise.
For example, what microtasks are enqueued with the following code?
const p1 = Promise.resolve("A");
const p2 = new Promise(resolve => resolve(p1));
p2.then(() => console.log("THEN"));
I have found no way to inspect the MicrotaskQueue in V8. After "reading" the ECMA specification of "Promise Resolve Functions", this is what I understood:
The call resolve(p2)
in the executor of Promise p2
enqueues a microtask that chains p1
to p2
. Lets call it the chaining microtask.
After the block of code is executed, the stack is empty and V8 processes the microtask queue. The queue contains only the chaining microtask.
The chaining microtask calls the then
method of p1
passing as callback functions the resolve
and reject
functions of p2
.
p1
is a resolved promise therefore the call to then
enqueues a new microtask to execute the then callbacks. Lets call it p1-then-p2 microtask.
The microtask queue now contains only the p1-then-p2 task.
V8 executes the p1-then-p2 task. The task enqueues a new microtask to execute the last then
in the code: p2.then(() => console.log("THEN"))
. Lets call it p2-then-console.
The microtask queue now contains only the p2-then-console task. V8 executes the task printing "THEN" in console.
The microtask queue is empty, the program exits.
Do I understood correctly?
Do I understood correctly?
Yes.
However, don't write code that will depend on the order of microtasks. This is specified in detail for deterministic results across js implementations, not for user code to rely on. It might even change with ECMAScript versions.