同一请求连续多次调用返回的数据没有按照请求顺序返回的问题解决

3次阅读

共计 664 个字符,预计需要花费 2 分钟才能阅读完成。

说在前面

在项目开发过程中遇到一种情况,在一个页面中某一请求需要连续多次调用的情况。本想着使用 axios 连续调用同一接口就完事,后面发现由于每次请求返回的顺序没有按照请求的顺序返回。经过一番查询,发现可以使用 Promise 来解决这一问题。

// curList 是连续调用接口的数组
curList.forEach(item => {
  // 为了让请求结果按照请求顺序返回,使用 Promise 方法
  tempList.push(new Promise((resolve, reject) => {
      axios.post(queryShopStatusByDate, {
        shopId: item.shopId,
        startDate: moment(new Date()).format('YYYY-MM-DD'),
        endDate: moment(new Date()).format('YYYY-MM-DD'),
        shipmentType: '89'
      }).then(res => {return resolve(res.data.result.totalPrice)
      }).catch(err => {return resolve('')
      })
    })
  )
});

Promise.all(tempList).then(res => {
  // 根据当前标签页状态对数组进行赋值
  this.activeIn === 0 ? this.personalSaleList = res : this.groupSaleList = res;
}).catch(err => {this.$toast('网络错误,接口调用失败!')
});

这样就解决了!

正文完
 0