{ console.log("F" /> { console.log("F" /> { console.log("F"/>

JS promise's handlers are executing in weird order

39 Views Asked by At

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.

1

There are 1 best solutions below

0
Alexander Nenashev On

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 second then() you queue the 2nd and 4th ones from the new promises. To fix you should queue all ones from the original promise:

const myPromise = new Promise((resolve, reject) => {
  resolve("Original resolution");
});

myPromise
  .then((result) => {
    console.log("First .then() block:", result);
  })
myPromise
  .then((result) => {
    console.log("Second .then() block:", result);
  });

myPromise
  .then((result) => {
    console.log("Third .then() block:", result);
  })
myPromise
  .then((result) => {
    console.log("Fourth .then() block:", result);
  });