简体   繁体   English

Javascript:等待循环内问题

[英]Javascript: await inside of loop issue

I want to use Eslint plugin in my project with Webpack but it does not let me use await inside the loop.我想在我的项目中使用 Eslint 插件 Webpack 但它不允许我在循环内使用await

According to Eslint docs it recommends to remove await from the loop and just add a Promise after.根据 Eslint 文档,它建议从循环中删除await并在之后添加一个Promise

Wrong example:错误的例子:

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

Correct example:正确的例子:

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

But in my code I just merge data into one array which comes from HTTP request:但在我的代码中,我只是将数据合并到一个来自 HTTP 请求的数组中:

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

Is it possible to remove await from this loop and add Promise just for array concatenation?是否可以从此循环中删除await并添加Promise仅用于数组连接? I don't have an idea how to do it...我不知道该怎么做...

If you like one-liners.如果你喜欢单线。

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

In this case, the map method returns a bunch of promises, based on the URL, and your getData method.在这种情况下,map 方法基于 URL 和您的getData方法返回一堆承诺。 The Promise.all waits until all of your promises will be resolved. Promise.all等到您的所有承诺都得到解决。 These promises run parallel.这些承诺并行运行。

You can use promise like this:您可以像这样使用 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;
   })
  }

If I'm understanding you correctly, your getData function returns an array?如果我对您的理解正确,您的getData function 返回一个数组?

Using the one-liner supplied by Anarno , we can wait until all promises are resolved and then concatenate all the arrays.使用Anarno提供的单线,我们可以等到所有的承诺都得到解决,然后连接所有的 arrays。

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

let finalArray = [];
allResults.forEach((item) => finalArray = finalArray.concat(item));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM