returnsFirstPromise()
.then((firstResolveVal) => {
return returnsSecondValue(firstResolveVal)
.then((secondResolveVal) => {
console.log(secondResolveVal);
})
})
returnsFirstPromise()
.then((firstResolveVal) => {
returnsSecondValue(firstResolveVal)
})
.then((someVal) => {
console.log(someVal);
})
We invoke a second .then(). It’s supposed to handle the logic for the second promise, but since we didn’t return, this .then() is invoked on a promise with the same settled value as the original promise!
When done correctly, promise composition is a great way to handle situations where asynchronous operations depend on each other or execution order matters.
If we need multiple async operations to run without particular order that each promise don't depend on each other, then we could use Promise.all(argumentArray of multiple promises).
Promise.all() accepts an array of promises as its argument and returns a single promise. That single promise will settle in one of two ways:
- If every promise in the argument array resolves, the single promise returned from Promise.all() will resolve with an array containing the resolve value from each promise in the argument array.
- If any promise from the argument array rejects, the single promise returned from Promise.all() will immediately reject with the reason that promise rejected. This behavior is sometimes referred to as failing fast.
example:
let myPromises = Promise.all([returnsPromOne(), returnsPromTwo(), returnsPromThree()]);
myPromises
.then((arrayOfValues) => {
console.log(arrayOfValues);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});