Skip to content Skip to sidebar Skip to footer

What Happen When We Return A Value And When We Return A Promise.resolve From A Then() Chain, In The Microtask Queue?

Here I have a promise that simply resolved. let promise = new Promise((resolve,reject)=>{ resolve('resolved'); }); The confusion for me starts when I use a Promise for ret

Solution 1:

The thens of Promises resolve during a microtask. Inside a .then, if you return a plain value, like 2 or 3, the next .then chained onto it will run the next time the call stack is clear. But if you return a Promise, it has to be unwrapped first before proceeding to the next .then.

In your first code, once the call stack is clear, the first microtasks run. One of them "unwraps" the Promise.resolve(2) and queues up the .then callback in the microtask queue. In contrast, the 3 doesn't need to be unwrapped, so its .then runs immediately at that point, without having to wait, logging 3.

The top task of the microtask queue is then the 2's .then, logging 2.

All this said, in real code, you shouldn't have to rely on this sort of timing, since it's a bit confusing - if it's an issue, best to re-structure the code so that it isn't something to worry about.

Solution 2:

Because you are returning a new Promise in case 1, it will get resolved in the next tick.

Each time the micro task Q is searched the promises that are in the Q get resolved (not only promises, but this is relevant for this question). In case 1 you get Promise.resolve(2) getting resolved at the same time resolve=>{ console.log(resolve) return 3; } gets resolved.

Now you next micro Q has the enclosing promise of Promise.resolve(2) on the Q. This adds a delay between the two cases.

Post a Comment for "What Happen When We Return A Value And When We Return A Promise.resolve From A Then() Chain, In The Microtask Queue?"