Promise.all()在项目中获取多个异步请求

Promise.all()简单地理解是:可以将多个Promise实例组合成一个新实例,并且仅在所有实例都为fulfilled时组合后的Promise才会变成fulfilled,任意一个实例被rejected,那么组合后的Promise就变为rejected

 1 const p1 = new Promise((resolve, reject) => {
 2   resolve('success')
 3 })
 4 
 5 const p2 = new Promise((resolve, reject) => {
 6   resolve('success')
 7 })
 8 
 9 const p3 = new Promise((resolve, reject) => {
10   reject('failed')
11 })
12 
13 Promise.all([p1, p2])
14   .then(result => {
15     console.log(result)
16   })
17   .catch(err => {
18     console.log(err)
19   })
20 // ['success', 'success']
21 
22 Promise.all([p1, p3])
23   .then(result => {
24     console.log(result)
25   })
26   .catch(err => {
27     console.log(err)
28   })
29 // failed

Promise.all()的结果时一个数组,和传入的Promise实例数组顺序一致,若rejected,则传入第一个rejected的结果。

如果内部Promise实例有catch方法,则reject时会调用自身的reject,否则调用外部catch。

在多个请求中使用Promise.all()可以实现多个请求同时完成的效果。下面是一个项目中使用的例子:

1 const param =this.postdata
2 Promise.all([this.$post('admin/listBoardDataV2', param), this.$post('admin/listAllTopList', param)])
3     .then(([previousRes, res]) => {
4     // ...      
5 })
posted @ 2022-04-08 16:52  晚安NN  阅读(497)  评论(0)    收藏  举报