在 for 循环中使用 await 是好的实践么?为什么 eslint 会提示不要这样使用?
在 for 循环中使用 await 是好的实践么?为什么 eslint 会提示不要这样使用?
15 回复
@atian25 这是eslint的提示信息:Unexpected await inside a loop. (no-await-in-loop);我用的是airbnb的配置。
for (let i = 0; i < 10; i += 1) {
await xxx;
}
@meiwhu 其实 eslint 的文档非常好的,你用后面的那个报错名一看就知道了 https://eslint.org/docs/rules/no-await-in-loop
又get到一个技能啊
不好的写法
async function foo(things) {
const results = [];
for (const thing of things) {
results.push(await bar(thing));
}
return baz(results);
}
好的写法
async function foo(things) {
const results = [];
for (const thing of things) {
results.push(bar(thing));
}
return baz(await Promise.all(results));
}
并不是会触发ESLint规则警告的就是不好的用法,正像3楼所说,ESLint官方提供了文档,解释了因为什么原因设计了这一项规则,其中也给出了什么时候使用这个规则、什么时候不适合使用这个规则的建议。
怎么写看你的具体需求。for中的代码需要控制执行顺序的话用await;不需要的话就可以不加await,把promise抛给下游去await,这样下游如果是异步执行的话效率高。 还有一种是async generator function,感兴趣可以了解一下。