promise. All principle
Promise. The all () method is used to wrap multiple promise instances into a new promise instance.
const p = Promise.all([p1, p2]);
Status response
The state of P is determined by P1 and P2, which are divided into two cases.
(1) Only when the states of P1 and P2 become full can the state of P become full. At this time, the return values of P1, P2 and P3 form an array and are passed to the callback function of P.
(2) As long as one of P1 and P2 is rejected, the state of P becomes rejected. At this time, the return value of the first rejected instance will be passed to the callback function of P.
Differences
p1、p2
Instance.catch
And.promise.all()
of.catch
const p1 = new Promise((reslove) => {
Reslove ('successful callback ')
}).then(res => res).catch(err => err)
const p2 = new Promise((reslove, reject) => {
Reject ('error reported ')
}).then(res => res).catch(err => err)
export default function() {
return Promise.all([p1, p2]).then((res) => {
console. Log (RES) ["successful callback", "error reported"]
}).catch((err) => {
console.log(err)
})
}
const p1 = new Promise((reslove) => {
Reslove ('successful callback ')
}).then(res => res)
const p2 = new Promise((reslove, reject) => {
Reject ('error reported ')
}).then(res => res)
export default function() {
return Promise.all([p1, p2]).then((res) => {
console.log(res)
}).catch((err) => {
console. Error in log (ERR)
})
}
Code parsing
- Enter each of the parameters in the array
promise
Success is returned only when all instances return success. Multiple instances are returnedpromise
Object successfully returns an array of values; promise.all
If one of the instances in the parameter is a failed callback, you want to execute it.then
Method, the failed instance needs to be used.catch
Method, which will get the results of failure and success. The returned result is an array; If you don’t want to do it.then
Method, the instance object in the parameter is not used.catch
Yes- The input parameter is an array that can
Pass basic type value
, orpromise
Object.
Promise. Race usage
As the name suggests, promse Race means race, which means promise Which result in race ([P1, P2, P3]) gets faster, it will return that result, regardless of whether the result itself is in success or failure status.
let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
},1000)
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject('failed')
}, 500)
})
Promise.race([p1, p2]).then((result) => {
console.log(result)
}).catch((error) => {
console. Log (error) // open 'failed'
})