我有两个版本的异步函数
async function asyncRecurseOne(i){
try{
console.log(i)
i = i +1;
await asyncRecurseOne(i)
}catch(ex){
console.log(ex);
}
}
asyncRecurseOne(0);
Run Code Online (Sandbox Code Playgroud)
这导致最大调用堆栈大小超过 6300 左右
6246
6247
6248
RangeError: Maximum call stack size exceeded
at asyncRecurseOne (/home/amit/Projects/NodeJs/MJS/recurse.js:38:17)
at asyncRecurseOne (/home/amit/Projects/NodeJs/MJS/recurse.js:36:15)
Run Code Online (Sandbox Code Playgroud)
现在在另一个版本中,我使用 sleep 方法执行以下操作
let sleep = (time) => new Promise((resolve) => setTimeout(resolve, time))
async function asyncRecurseTwo(i){
try{
console.log(i)
i = i +1;
await sleep(100);
await asyncRecurseTwo(i)
}catch(ex){
console.log(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
而且这个函数没有给出解决问题的最大调用堆栈大小,我在我的系统上运行直到记录了 20000。
第二个函数如何在不达到最大堆栈大小问题的情况下继续执行?
javascript ×1