I am learning promise chaining and I stumbled upon a doubt. Consider the below promise chain –
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 10000);
});
myPromise
.then(handleFulfilledA, handleRejectedA) // first then
.then(handleFulfilledB, handleRejectedB) // second then
.then(handleFulfilledC, handleRejectedC); // third then
The promise constructor returns a promise object myPromise
. The handleFulfilledA
and handleRejectedA
are attached to the [[PromiseFulfillReactions]]
and [[PromiseRejectReactions]]
of myPromise
object. The second and the third then
method will be called before myPromise
is resolved as myPromise
takes 10 seconds.
What happens internally when the second and the third .then method is encountered?
I tried to find an answer and came to know that each then
method returns a new Promise
object. Let’s call them promiseB
and promiseC
. The handleFulfilledB
and handleRejectedB
are attached to the [[PromiseFulfillReactions]]
and [[PromiseRejectReactions]]
of promiseB
. Similarly, handleFulfilledC
and handleRejectedC
are attached to promiseC
.
But if this is the case, when myPromise
is fulfilled and its [[PromiseFulfillReactions]]
are executed, how will its reactionhandlers(handleFulfilledA
, handleRejectedA
) know that it has to resolve or reject promiseB
? How will the handler come to know that the then
to which it was passed to has created a promise which is promiseB
? In other words, how is the connection between the handlers and the new promises established?”