JavaScript Promise.all: Execute Multiple Promises Concurrently
Promise.all is a method in JavaScript that takes an array of promises as input and returns a new promise. This new promise resolves when all the input promises have resolved, or rejects if any of the input promises reject.
The returned promise resolves with an array of the resolved values from the input promises, in the same order as the input promises. If any of the input promises reject, the returned promise rejects with the reason of the first rejected promise.
Here is an example of using Promise.all:
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 1 resolved');
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 2 resolved');
}, 2000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise 3 resolved');
}, 3000);
});
Promise.all([promise1, promise2, promise3])
.then((values) => {
console.log(values);
})
.catch((error) => {
console.error(error);
});
In the example above, Promise.all is used to wait for all three promises to resolve. Once all three promises have resolved, the 'then' callback is called with an array of their resolved values. If any of the promises reject, the 'catch' callback is called with the reason of the first rejected promise.
原文地址: https://www.cveoy.top/t/topic/x8t 著作权归作者所有。请勿转载和采集!