I don’t understand the order in which tasks are sent to the microtasks queue.
I expected this output: 1, 11, 111, 2, 3, 12, 122
But received: 1, 11, 111, 2, 12, 122, 3
Does compiler register the whole chain or it can see only the next then
?
How does it work?
Promise.resolve()
.then(() => console.log(1))
.then(() => console.log(2))
.then(() => console.log(3));
Promise.resolve()
.then(() => console.log(11))
.then(() => console.log(12));
Promise.resolve()
.then(() => console.log(111))
.then(() => console.log(122));
2
Answers
Linked
Promise.then
calls are nested, not sequentialAccording to MDN’s Microtask guide,
However, this does not apply to linked
.then
calls. If it did, you would have to operate under the assumption that linked.then
calls are all linked to the original Promise and not each other. You can actually see that each linked.then
call is linked to the result of the previous.then
:In this example, you can see that in order for the next
.then
to be added to the queue, it needs the result of the previous.then
call.To further illustrate that linked
Promise.then
calls are nested and not sequential, you can create both nested and sequential microtasks to see what happens.Microtasks
Nested
When this example is run, it clearly illustrates the same results you received from linking
.then
calls.Sequential
When you run this example, it demonstrates the aforementioned quote from MDN. It functions similarly to how you thought linking
.then
calls would, but this is not how Promises work.Promise conceptualization
If you don’t care about this part, you can skip it. This is simply a quick implementation of a
Promise
usingqueueMicrotask
. Hopefully it can help you see the nesting of linked.then
calls and their associated microtasks.The order of the console logs are not guaranteed. There are 45 possible outcomes each time you run your script.
Here are your rules:
Demonstration
I put together a naïve script that will generate each permutation and validate the order based on the promise logic you have provided.