In simple words, a promise is a placeholder for a value that's going to be available sometime later.
The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.
Try it at - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Promises are useful when handling asynchoronous operations.
Promise.all()
is a built-in helper that accepts an array of promises (or generally an iterable). The function returns a promise:
const allPromise = Promise.all([promise1, promise2, ...]);
Then you can extract promises resolved values using a then
-able syntax:
allPromise.then(values => {
values; // [valueOfPromise1, valueOfPromise2, ...]
}).catch(error => {
error; // rejectReason of any first rejected promise
});
or async/await
syntax:
try { const values = await allPromise;
values; // [valueOfPromise1, valueOfPromise2, ...]
} catch (error) {
error; // rejectReason of any first rejected promise
}
If all promises are resolved successfully, then allPromise
fulfills with an array containing fulfilled values of individual promises. The order of promises in the array does matter — you'll get the fulfilled values in that order.
But if at least one promise rejects, then allPromise
rejects right away (without waiting for other promises to resolve) with the same reason.
Top comments (0)