Reputation: 891
How does promise chaining inside a function works? In the following code:
promiseA() {
return anotherPromise().then( res => {
// resolution of promise A
})
};
promiseB() {
promiseA().then( res => {
// resolution of promise B
})
}
I tested this code and I get that resolution of B is always done after A is resolved. However, I can't find any documentation. Will resolution of promise B always happens after resolution of Promise A done, or is my test just one case of race condition?
Upvotes: 1
Views: 465
Reputation: 136134
Yes, it will always resolve A first before B. If you re-wrote your code without the indirection of separate methods what you have is simply:
anotherPromise().then(...A...).then(...B...)
And that should make it clear that the code inside the A then
must always run before the code inside the B then
.
A simple test confirms. You can run this a million times and A will always resolve before B:
function anotherPromise(){
return new Promise((resolve,reject) => {
setTimeout(resolve,1000);
});
}
function promiseA(){
return anotherPromise().then( res => {
console.log("Resolve promiseA");
return res;
});
}
function promiseB(){
return promiseA().then(res => {
console.log("Resolve promiseB");
return res;
})
}
promiseB();
Upvotes: 2
Reputation: 4971
You have invoked the Promise A inside Promise B, so by logic Promise A should be resolved before Promise B.
Promise.then( // resolved first )
.then( // resolved second )
Upvotes: 0