【问题标题】:使 for 循环等待直到数据从 API 返回
【发布时间】:2022-01-22 16:52:47
【问题描述】:

我有这样的结构:

methods: {
  function() {
    //some stuff in here    

    for(let i=0; i < array.length; i++) {
      //Problem in here or around here
      //in here I send something to my API and want to get data back
    }
  }
}

解释我的工作:我有一个array,我想在其中循环,对于每个loop,我将data 发送到我的API 并在@987654327 中返回data @。

我的问题:我总是以不同的顺序取回数据,因为其中一个数据可能更大,并且比其他数据需要更长的时间。

示例: 我发送 Array = [1,2,3,4] 并希望以正确的顺序取回它。但是12,3,4 需要更多的时间,而且我得到的数据比[2,3,4,1] 按顺序返回的数据要多。

我如何分配我的for-loop 等到第一个数据返回后再继续?

谢谢!

【问题讨论】:

  • 这能回答你的问题吗? Using async/await with a forEach loop
  • 它是否像使用 forEach 一样使用 for 循环?
  • Promise 或生成器函数可能会有所帮助,具体取决于场景。

标签: javascript vue.js vuejs2 bootstrap-vue


【解决方案1】:

一旦您阅读了async/await,您仍然希望并行运行您的请求以节省时间,而不是按顺序运行。 Promise.all 在这里帮助:

async function fetchData () {

  const resultsInOrder = await Promise.all(
    // pass an array of Promises
    array.map(element =>
      fetch(/* some arguments based on the element's data */)
        .then(res => res.json())
    )
  )
  // do something with results
}

【讨论】:

  • 地图函数没有返回承诺。
  • @EstusFlask 不,array.map() 应该返回一个 Promise 数组。 Promise.all 将其作为单个参数,并在它们全部完成后解析为已解析值的数组,或者如果数组中的任何 Promise 完成,则拒绝。
  • 我的意思是没有返回语句,你得到一个未定义的数组
  • 哦,我明白了,我的错。我修复了代码。
猜你喜欢
  • 1970-01-01
  • 2019-03-01
  • 2019-11-03
  • 2018-09-07
  • 2015-09-10
  • 2019-05-22
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
相关资源
最近更新 更多