【问题标题】:For loop to call API function and wait for itFor循环调用API函数并等待它
【发布时间】:2020-06-28 15:29:50
【问题描述】:

我的数据循环进入 API,如下所示。如何确保在第一次迭代完成时调用下一次迭代?图片我的 API 需要一秒钟来处理每个元素

saveMyData(){
  this.elements.forEach(element => {
    CALL_MY_API.read(element)
    .then(response =>  {
        // comes here in 1 second
        // do something with response
    }
    .catch(error => {
       this.showError(error)
    })
 })
}

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

这会并行启动一堆异步操作。我认为这不是您想要的,您希望等待一个真正完成后再开始下一个。

如果你可以使用async/await 语法是最简单的:

async saveMyData() {
  for (const element of this.elements) {
    try {
      const response = await CALL_MY_API.read(element)
      // do something with response
    } catch (error) {
      this.showError(error)
    }
  }
}

如果不能,则需要手动链接承诺:

saveMyData() {
  // Start with an immediately resolved promise.
  let promise = new Promise((resolve, reject) => resolve())
  // Add each element to the chain.
  this.elements.forEach(element => {
    promise = promise.then(() => {
      return CALL_MY_API.read(element)
        .then(response => {
          // do something with response
        })
        .catch(error => {
          this.showError(error)
        })
    })
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-10
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多