Part from MDN
Promise.all(iterable)
- This instance is resolved when all promises in iterable arguments are “resolved” or when no promises are included in the arguments
- If the promise parameter has a failed (Rejected), this instance calls back failed (Reject), which is the result of the first failed promise.
Let’s look at example 1
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promiseList = [promise1,promise2]
Promise.all(promiseList)
.then((values) = > {
console.log(20, values) // Outputs 3, 42
})
.catch(err= > {
console.log(22, err)
})
Copy the code
Example 2
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) = > reject('I'm Promise_1 to fail'))
const promise4 = new Promise((resolve, reject) = > reject('I'm Promise_2 to fail'))
const promiseList = [promise1,promise2,promise3, promise4]
Promise.all(promiseList)
.then((values) = > {
console.log(20, values) // Will not go through the callback here
})
.catch(err= > {
console.log(22, err) // The output 'I am a failed reject' is interrupted by returning the first reject
})
Copy the code
Problem: Unable to locate errors accurately, hence promise.allSettled
Promise.allSettled()
- The promise.allSettled () method returns a Promise settled after all given promises have been settled or rejected, with an array of objects, each representing the corresponding Promise result.
- We can use this method if we request multiple interfaces and need to count the number of errors.
example
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) = > reject('I'm Promise_1 to fail'))
const promise4 = new Promise((resolve, reject) = > reject('I'm Promise_2 to fail'))
const promiseList = [promise1,promise2,promise3, promise4]
Promise.allSettled(promiseList).then(values= >{
console.log(26, values)
})
Copy the code
Output result:
- This promise is a big pity, which is pending, and rejected.
Promise. All () template
const arr = [1.2.3.4]
Promise.all(arr.map(val= >createPromise(val))).then(res= >{
console.log(36, res)
})
function createPromise(val) {
return new Promise(resolve= > resolve(val))
}
Copy the code