替代内部循环 for ... of 和 while(true)
Alternative to looping inside for ... of and while(true)
很多时候我最终会编写内部有 await
s 的循环,以便按顺序执行某些任务或在迭代之间实现一定的间隔。
例如:
for (const item of items) {
await doSomthing(item);
}
或:
while(true) {
await doSomeTask();
await delay(60000);
}
然而,ESLint 正在训斥我写这种代码。
当我不想同时 运行 所有异步任务,而是想 运行他们的节奏很慢?
ESLint is reprimanding me for writing this kind of code.
这里的解决方案是禁用 ESLint - 单独禁用这些行,或者 that horrible rule 一般禁用。甚至规则文档本身也说“在许多情况下 [...] 在循环中使用 await
是有意义的,建议通过标准 ESLint 禁用注释 禁用规则".
您正在编写的代码非常适合按顺序执行任务。如果你想避免它,只有递归作为 linter 无法检测到的替代方案:-)
您可以使用递归函数来实现相同的效果,这使您可以更充分地利用您正在执行的操作的异步特性。您的主线程可以继续做其他事情,而不是等待 for
循环结束 - 任何依赖于该部分完成的代码都可以在您传入的回调函数中执行。
function asynchronousFunction(thing){
//do something
console.log('doing something')
return new Promise(resolve => {
setTimeout(e => resolve(), 1000)
})
}
async function doSomething(arrayOfThings, next){
const thing = arrayOfThings.pop()
const responseFromAsyncFunction = await asynchronousFunction(thing)
console.log('after', arrayOfThings.length)
if(arrayOfThings.length) doSomething(arrayOfThings, next)
else next()
}
const myData = [1,2,3,4,5]
doSomething(myData.slice(0), function(){ console.log('done') })
很多时候我最终会编写内部有 await
s 的循环,以便按顺序执行某些任务或在迭代之间实现一定的间隔。
例如:
for (const item of items) {
await doSomthing(item);
}
或:
while(true) {
await doSomeTask();
await delay(60000);
}
然而,ESLint 正在训斥我写这种代码。
当我不想同时 运行 所有异步任务,而是想 运行他们的节奏很慢?
ESLint is reprimanding me for writing this kind of code.
这里的解决方案是禁用 ESLint - 单独禁用这些行,或者 that horrible rule 一般禁用。甚至规则文档本身也说“在许多情况下 [...] 在循环中使用 await
是有意义的,建议通过标准 ESLint 禁用注释 禁用规则".
您正在编写的代码非常适合按顺序执行任务。如果你想避免它,只有递归作为 linter 无法检测到的替代方案:-)
您可以使用递归函数来实现相同的效果,这使您可以更充分地利用您正在执行的操作的异步特性。您的主线程可以继续做其他事情,而不是等待 for
循环结束 - 任何依赖于该部分完成的代码都可以在您传入的回调函数中执行。
function asynchronousFunction(thing){
//do something
console.log('doing something')
return new Promise(resolve => {
setTimeout(e => resolve(), 1000)
})
}
async function doSomething(arrayOfThings, next){
const thing = arrayOfThings.pop()
const responseFromAsyncFunction = await asynchronousFunction(thing)
console.log('after', arrayOfThings.length)
if(arrayOfThings.length) doSomething(arrayOfThings, next)
else next()
}
const myData = [1,2,3,4,5]
doSomething(myData.slice(0), function(){ console.log('done') })