【发布时间】: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