我无法弄清楚为什么调用recSetTimeOut()不会导致堆栈溢出错误,而recPromise()会导致堆栈溢出错误。
const recSetTimeOut = () => {
console.log('in recSetTimeOut');
setTimeout(recSetTimeOut, 0)
};
recSetTimeOut();Run Code Online (Sandbox Code Playgroud)
const recPromise = () => {
console.log('in recPromise');
Promise.resolve().then(recPromise);
}
recPromise();Run Code Online (Sandbox Code Playgroud)
为什么会发生?它们之间有什么区别?
你能解释一下幕后的过程吗?
编辑更多信息
在Node.js v12.1.0和运行以下代码段Chrome DevTools:
const recSetTimeOut = () => { setTimeout(recSetTimeOut, 0); }
recSetTimeOut();
Run Code Online (Sandbox Code Playgroud)
结果Node:无错误。
结果Chrome:无错误。
const recPromise = () => { Promise.resolve().then(recPromise); }
recPromise();
Run Code Online (Sandbox Code Playgroud)
结果Node:
严重错误:无效的表大小分配失败-JavaScript堆内存不足
结果Chrome:浏览器崩溃。
promise/a +规范第2.2.4条规定:
在执行上下文堆栈仅包含平台代码之前,不得调用onFulfilled或onRejected.
然后在笔记中说明:
这里的"平台代码"意味着引擎,环境和承诺实现代码.实际上,这个要求确保onFulfilled和onRejected异步执行,然后调用事件循环,然后调用新堆栈.
这样做的目的是确保当链中存在大量onFulfilled函数时,它们的执行不会导致线程阻塞吗?
或者在我不读的行之间还有其他什么东西吗?