This is my code:
const myPromise = new Promise((resolve, reject) => {
resolve("Original resolution");
});
myPromise
.then((result) => {
console.log("First .then() block:", result);
})
.then((result) => {
console.log("Second .then() block:", result);
});
myPromise
.then((result) => {
console.log("Third .then() block:", result);
})
.then((result) => {
console.log("Fourth .then() block:", result);
});
So from this i was expecting then handlers to execute in sequence and log First, Second, Third and Fourth log statements.
But the output is as follows:
First .then() block: Original resolution
Third .then() block: Original resolution
Second .then() block: undefined
Fourth .then() block: undefined
I studied about microtask queue and event loop but did not find why the order of enqueuing handlers is not in sequence.
Or if they are enqueued sequentially, then why executed in different order because FIFO is not maintained in this case.
Promise::then()creates a new promise which has it's own FIFO. So first you queue the 1st and 3rd promises from the original promise. Then with the secondthen()you queue the 2nd and 4th ones from the new promises. To fix you should queue all ones from the original promise: