当我运行以下程序时
async function functionOne(){
抛出新的错误(‘错误在这里打印完整的堆栈’);
等待新的Promise((resolve)=> { setTimeout(()=> {resolve(); …
因为在第一个代码中,一切都要到了 Error 与事件循环相同。
Error
在异步回调之前,来自 setTimeout ,可以进入调用堆栈(堆栈跟踪是由它构建的),调用堆栈必须为空。
setTimeout
所以,因为第一个代码运行所有同步,直到 Error 呼叫,所有这些呼叫都在呼叫堆栈中。但在第二种方法, Error 被称为 await 一个 setTimeout 呼叫。当。。。的时候 setTimeout 已经完成了。事件循环将回调放回堆栈,为此,调用堆栈 必须 是空的。
await
所以现在,你没有 functionTwo &安培; functionThree 在调用堆栈上,这就是它们不出现的原因。
functionTwo
functionThree
Ť 的 堆栈跟踪是发生错误时堆栈的状态。 强>
以下是两个代码中堆栈发生情况的粗略解释:
的 第一码 强>
1) functionThree is pushed into the stack 2) functionTwo is pushed into the stack 3) functionOne is pushed into the stack 4) Error is thrown
的 第二码 强>
1) functionThree is pushed into the stack 2) functionTwo is pushed into the stack 3) functionOne is pushed into the stack 4) awat ...setTimeout is called 5) All 3 functions return a Promise 6) The stack is empty ... setTimeout ends Next tick of the event loop 1) setTimeout callback is called 2) Error is thrown
我建议观看此视频,了解所有这些是如何工作的:
无论如何,事件循环到底是什么 菲利普罗伯茨
在您可以使用的Node.js的newests版本上 --async-stack-traces 使用异步代码时,标记有一个改进的堆栈跟踪。
--async-stack-traces
你可以在这里阅读更多相关内容 https://v8.dev/blog/fast-async