JS: Promise.all
Promise.all(iterable)-
iterable is a Iterable Object. Each yield should be a promise. If not, it is treated as resolved value of fulfilled promise.
return a new promise with a settled state and combined promise results. The state of the new promise and resolved value is:
- Fulfilled → when all promises fulfills. value is an array of resolve values in same order as input.
- Rejected → when any promise is rejected, value is the value of first reject. the first promise that reject will immediately reject the whole. (other promises are ignored)
if the input iterable is empty, result is also fulfilled.
Example. all resolved
const p1 = Promise.resolve(1); const p2 = new Promise((rs) => setTimeout(() => rs(2), 1000)); const p3 = Promise.resolve(3); Promise.all([p1, p2, p3]) .then( (results) => console.log(results), (err) => console.error(err), ); // [ 1, 2, 3 ]
Example. a rejection
const promises = [ Promise.resolve("ok"), Promise.reject("oh fail"), Promise.resolve("also ok"), ]; Promise.all(promises) .then( (x) => console.log("fulfilled with value:", x), (x) => console.log("rejected with value:", x), ); // rejected with value: oh fail