当您有需要按顺序完成的事情列表时,让异步函数调用自身是个好主意吗?
例子:
async continueWork(){
if(!this.list.length)
return;
var next = this.list.shift();
// do things with next
await this.continueWork();
}
如果列表非常大怎么办?它会引起问题吗?
最佳答案
是的,这可能会导致问题。每个 continueWork
调用都被放入调用堆栈,在最后一个 continueWork
之上,这可能导致溢出:
let i = 0;
async function continueWork() {
i++;
if (i < 1e5) {
await continueWork();
}
}
continueWork()
.then(() => console.log('ok'))
.catch((err) => {
console.log('err');
console.log(err.stack);
});
您可以通过在 continueWork
递归调用自身之前 await
ing 一些东西来修复它,这样调用堆栈就不会堆积起来:
let i = 0;
async function continueWork() {
i++;
await Promise.resolve();
if (i < 1e5) {
await continueWork();
}
}
continueWork()
.then(() => console.log('ok'))
.catch((err) => {
console.log('err');
console.log(err.stack);
});
重要的是确保在调用堆栈清空之前没有大量的同步 函数调用。 await
(或 .then
)确保 await
或 .then
回调之后的内容在microtask(仅在调用堆栈清除后才会发生)。
关于javascript - 调用自身的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349360/