【问题标题】:Javascript: await inside of loop issueJavascript:等待循环内的问题
【发布时间】:2021-03-23 15:47:03
【问题描述】:

我想在我的项目中通过 Webpack 使用 Eslint 插件,但它不允许我在循环中使用 await

According to Eslint docs 建议从循环中删除 await 并在之后添加 Promise

错误的例子:

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Bad: each loop iteration is delayed until the entire asynchronous operation completes
    results.push(await bar(thing));
  }
  return baz(results);
}

正确示例:

async function foo(things) {
  const results = [];
  for (const thing of things) {
    // Good: all asynchronous operations are immediately started.
    results.push(bar(thing));
  }
  // Now that all the asynchronous operations are running, here we wait until they all complete.
  return baz(await Promise.all(results));
}

但在我的代码中,我只是将数据合并到一个来自 HTTP 请求的数组中:

async update() {
   let array = [];
   for (url of this.myUrls) {
      const response = await this.getData(url);
      array = await array.concat(response);
   }
}

是否可以从此循环中删除 await 并添加 Promise 仅用于数组连接?我不知道该怎么做...

【问题讨论】:

    标签: javascript async-await es6-promise eslint


    【解决方案1】:

    如果你喜欢单线。

    const array = await Promise.all(this.myUrls.map((url)=> this.getData(url)));
    

    在这种情况下,map 方法会根据 URL 和您的 getData 方法返回一堆承诺。 Promise.all 等到你的所有承诺都得到解决。这些承诺并行运行。

    【讨论】:

    • 移除回调中的awaitasync。它们不是必需的,也没有用。
    • 此技术假定服务器负载和速率限制可以立即触发整个请求循环。情况并非总是如此。
    【解决方案2】:

    你可以像这样使用promise:

     function update() {
       let array = [],req=[];
        for (url of this.myUrls) {
         req.push(this.getData(url));
        }
       return Promise.all(req).then((data)=>{
         console.log(data);
        return data;
       })
      }
    

    【讨论】:

      【解决方案3】:

      如果我的理解正确,您的 getData 函数会返回一个数组?

      使用Anarno 提供的单线,我们可以等到所有的承诺都得到解决,然后连接所有的数组。

      const allResults = await Promise.all(this.myUrls.map((url) => this.getData(url)));
      
      let finalArray = [];
      allResults.forEach((item) => finalArray = finalArray.concat(item));
      

      【讨论】:

        猜你喜欢
        • 2021-07-17
        • 2018-08-04
        • 2020-04-20
        • 1970-01-01
        • 1970-01-01
        • 2022-12-08
        • 2015-09-10
        • 2010-12-17
        • 2017-12-16
        相关资源
        最近更新 更多