【问题标题】:How to get last promise response if we have multiple api's call如果我们有多个 api 调用,如何获得最后一个承诺响应
【发布时间】:2021-05-15 14:35:38
【问题描述】:

我有一个数据数组,我正在使用 for 循环将这些数据发送到服务器。假设我们在 array 中有 3 个元素。它会同时调用 3 个 api,但我想要实现的是获得最后一个承诺解决响应,例如 3 个文件有 3 个不同的大小两个文件的大小很小,第三个文件的大小很大,这是有意义的,第三个文件将当大文件大小的承诺得到解决时需要一些时间我想控制那个响应。我真的很努力,但没有找到任何解决方案,有人可以帮助我。

for (let i = 0; i < selectedFiles.length; i++) {
      let bodyFormData = new FormData()
      bodyFormData.append('file', selectedFiles[i])

      const options = {
        onUploadProgress: (progressEvent) => {
          const { loaded, total } = progressEvent
          let percent = Math.floor((loaded * 100) / total)


          selectedFiles[i].percentage = percent

          this.setState({
            progressInfos: selectedFiles,
          })
        },
      }

      axios
        .post(`${config.apiPath}/api/fileUpload`, bodyFormData, options)
        .then((res) => {
        })
    } 

【问题讨论】:

  • 你需要使用Promise.all

标签: javascript reactjs ecmascript-6 axios fetch


【解决方案1】:

考虑使用Promise.all

let promises = [];
for (let i = 0; i < selectedFiles.length; i++) {
  /*...*/
  p.push(axios.post(`${config.apiPath}/api/fileUpload`, bodyFormData, options));
  /*...*/
}
Promise.all(p).then((res) => {
  console.log(res); // res[0], res[1], res[...n]
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2016-06-22
    • 2020-02-04
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多