promise应用

1、Promise.all()

在我们的异步调用时经常有这样一种场景:我们需要同时调用多个异步操作,但希望只有等所有的操作都完成后,我们才去执行响应操作

直接上demo

 1                 var p1 = new Promise((resolve, reject) => {
 2                     getMerchantDetail({merchantId: this.id, type: 37,}).then(res => {
 3                         resolve(res.data)
 4                     })
 5                 })
 6                 var p2 = new Promise((resolve, reject) => {
 7                     setTimeout(()=> {
 8                         getMerchantInfo({merchantId: this.id, type: 37,}).then(res => {
 9                             resolve(res.data)
10                         })
11                     }, 0);
12                 })
13                 var p3 = new Promise((resolve, reject) => {
14                     setTimeout(()=> {
15                         getMerchantAddress({merchantId: this.id, type: 37,}).then(res => {
16                             resolve(res.data)
17                         })
18                     }, 0);
19                 })
20                 var p4 = new Promise((resolve, reject) => {
21                     setTimeout(()=> {
22                         getMerchantList({merchantId: this.id, type: 37,}).then(res => {
23                             resolve(res.data)
24                         })
25                     }, 0);
26                 })
27 
28                 Promise.all([p1, p2, p3, p4]).then(values => {
29                     console.log(values);
30                 }).catch(reason => {
31                     console.log(reason)
32                 });

上面4个是提前定义好的接口请求,需要在接口请求成功之后,再进行下一步操作。

原文地址:https://www.cnblogs.com/zjingjing/p/14005319.html