(reproduced) Understanding and using Promise.all and Promise.race

Statement: This article is reproduced from: https://www.jianshu.com/p/7e60fc1be1b2

1. The use of Pomise.all

Promise.all can wrap multiple Promise instances into a new Promise instance. At the same time, the return values ​​of success and failure are different. When it succeeds, it returns an array of results, and when it fails, it returns the value of the first rejected failure state.

The specific code is as follows:

let p1 = new Promise((resolve, reject) => { resolve('成功了') }) let p2 = new Promise((resolve, reject) => { resolve('success') }) let p3 = Promse.reject('失败') Promise.all([p1, p2]).then((result) => { console.log(result) //['成功了', 'success'] }).catch((error) => { console.log(error) }) Promise.all([p1,p3,p2]).then((result) => { console.log(result) }).catch((error) => { console.log(error) // 失败了,打出 '失败' }) 

Promse.all is very useful when dealing with multiple asynchronous processes. For example, a page needs to wait for two or more ajax data to come back before it is displayed normally. Before that, only the loading icon is displayed.

Code simulation:

let wake = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time / 1000}秒后醒来`)
    }, time)
  })
}

let p1 = wake(3000)
let p2 = wake(2000) Promise.all([p1, p2]).then((result) => { console.log(result) // [ '3秒后醒来', '2秒后醒来' ] }).catch((error) => { console.log(error) }) 

It is important to note that the data order in the array of the successful result obtained by Promise.all is the same as the order of the array received by Promise.all, that is, the result of p1 comes first, even if the result of p1 is obtained later than that of p2. This brings a great benefit: in the process of requesting data in front-end development, occasionally there will be scenarios where multiple requests are sent and data is obtained and used according to the order of requests. Using Promise.all can undoubtedly solve this problem.

Second, the use of Promise.race

As the name implies, Promse.race means running, which means that whichever result in Promise.race([p1, p2, p3]) gets the fastest result will be returned, regardless of whether the result itself is a success state or a failure state.

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) // 打开的是 'failed' }) 

The principle is quite simple, but in practice, I haven't thought of any usage scenarios that will be used.


_________________________________________
The above is the original text.
Combined with comments, the role of Promise.race():
Used to bind with timers, you can test the response speed of some interfaces, analyze the user's network status, etc., such as wrapping a request and executing the timer after three seconds into a promise instance, and then adding it to the promise.race queue , when the request has not been responded for three seconds, you can give the user some hints, or some other operations. ————————— From Jianshu user: Wang Awang: https://www.jianshu.com/u/d70685084dc1
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324955127&siteId=291194637