Promise.all and promise. race
- Similarities:
- These are both
Promise
Method, and the parameter passed is aPromise
The array. - Will return one
Promise
The instance
- These are both
- The difference between:
- “All” : all that is passed in
Promise
It all ends up being converted tofulfilledState, is executedresolveCallback and will return values yes allPromise
theresolve
The callbackvalueThe array. One of them any of themPromise
forrejectState, is returnedPromise
The state of therejected. - Race: all incoming
Promise
Any one of them is statically converted tofulfilledorrejected, the corresponding callback will be executed.
- “All” : all that is passed in
If you feel vague, please click on MDN’s Promise introduction page
The sample code
Promise. All. The following code covers the various states that Promise can be in in all
// P1: Changes to the fullfilled state after 0.5 seconds
let p1 = new Promise((res,rej) = > {
setTimeout(() = >{
res("P1 call successful")},500)})//p2: directly changes to the RES state
let p2 = new Promise((res,rej) = > {
res("P2 call successful")})// P3: Changes to the Rejected state after 1s
let p3 = new Promise((res,rej) = > {
setTimeout(() = >{
rej("P3 failed...")},1000)})// P4: indicates the rejected state after 2s
let p4 = new Promise((res,rej) = > {
setTimeout(() = >{
rej("P4 failed...")},2000)})// pass p1, p2
Promise.all([p1,p2]).then(res= >{
console.log(res); // ['p1 call successful ','p2 call successful ']
}).catch(rej= > {
console.log(rej);
})
/ / to p3
Promise.all([p1,p2,p3]).then((res,rej) = > {
console.log(res);
}).catch(rej= > {
console.log(rej); //p3 failed...
})
/ / in p4
Promise.all([p1,p2,p3,p4]).then((res,rej) = > {
console.log(res);
}).catch(rej= > {
console.log(rej); //p3 failed...
})
Copy the code
Promise. Race. The following code covers the various states that can occur in a Promise in a race
// P1: Changes to the fullfilled state after 0.5 seconds
let p1 = new Promise((res,rej) = > {
setTimeout(() = >{
res("P1 call successful")},500)})//p2: directly changes to the RES state
let p2 = new Promise((res,rej) = > {
res("P2 call successful")})// P3: Changes to the Rejected state after 1s
let p3 = new Promise((res,rej) = > {
setTimeout(() = >{
rej("P3 failed...")},1000)})// P4: indicates the rejected state after 2s
let p4 = new Promise((res,rej) = > {
setTimeout(() = >{
rej("P4 failed...")},2000)})/ / to p1, p2
Promise.race([p1,p2]).then(res= >{
console.log(res) // P2 was called successfully
})
/ / to p1, p3
Promise.race([p1,p3]).then(res= > {
console.log(res) // call p1 successfully
}).catch(rej= > {
console.log(rej)
})
/ / to p3, p4
Promise.race([p3,p4]).then(res= > {
console.log(res)
}).catch(rej= > {
console.log(rej) //p3 failed...
})
Copy the code
The interview examination site
I’m sure you have some understanding of these two methods. What kind of questions will be asked in the interview?
Usage scenarios
Use all when you want to combine multiple asynchronous results. When you want to control the timing of an asynchronous operation, you can use a timer and a race.
Passing an empty array
What happens when our all and race pass in an empty array?
- All: the returned
Promise
Will enterfullfilled
State, then it will be executedresolve
To return an empty array - Race: the returned
Promise
It’s going to stay therependingState.
To understand why this race results this way, you can use the following handwritten implementation. But the reason for all method, I am also still exploring.
Handwritten implementation
Promise.all
function all(arr){
// Return a promise
return new Promise((res,rej) = > {
let length = arr.length // The number of promises passed in
let count = 0 // the number of fullfilled promises
const result = [] // Create an array of equal length to place the result
for(let i = 0; i < arr.length; i++){
arr[i].then(resolve= > {
result.push(resolve) // Store each result in the Result array
count ++ // Add one
// All promises are in the fullfilled state
if(count === length){
res(result) // Return the result
}
}).catch(e= > {
rej(e) // If there is an error, the loop is terminated and an error is returned})}})}Copy the code
Promise.race
function race(arr){
return new Promise((res,rej) = > {
for(let i = 0; i < arr.length; i++){
arr[i].then(resolve= > {
res(resolve) // A promise is completed and returns its value directly
}).catch(e= > {
rej(e) // If there is an error, the loop is terminated and an error is returned})}})}Copy the code