首页 > 解决方案 > Javascript:等待循环内的问题

问题描述

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

根据 Eslint 文档,它建议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仅添加数组连接?我不知道该怎么做...

标签: javascriptasync-awaites6-promiseeslint

解决方案


你可以像这样使用承诺:

 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;
   })
  }

推荐阅读