Currently, I am diving into the world of promise chaining and have encountered a question. Let's take a look at this example with a 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
After creating the myPromise
object using the promise constructor, the handlers handleFulfilledA
and handleRejectedA
are connected to it. Due to the 10-second delay in resolving myPromise
, the second and third then
methods will be executed before the resolution.
So, what really happens behind the scenes when encountering the second and third .then method?
I tried to research and found that each then
call generates a new Promise
object - let’s name them promiseB
and promiseC
. The handlers handleFulfilledB
and handleRejectedB
are associated with promiseB
, while handleFulfilledC
and handleRejectedC
are linked to promiseC
.
However, if this is accurate, how exactly do the original reaction handlers (handleFulfilledA
, handleRejectedA
) from myPromise
recognize they need to interact with promiseB
? In essence, how is the bridge between these handlers and the subsequent promises established?