[英]lose stack trace when using Promise.then vs. async-await
I have the following snippet implemented with Promise.then
:我使用Promise.then
实现了以下代码段:
function b() {
return Promise.resolve()
}
function c() {
throw new Error('error here')
}
const a = () => {
b().then(() => c());
};
a()
The stack trace output from the error only included function c
错误的堆栈跟踪输出仅包括函数c
VM57:6 Uncaught (in promise) Error: 343
at c (<anonymous>:6:9)
at <anonymous>:10:17
However, if I switch this to async-await as in:但是,如果我将其切换为 async-await,如下所示:
function b() {
return Promise.resolve()
}
function c() {
throw new Error('error here')
}
const a = async () => {
await b()
c()
};
a()
This time the stack trace included the whole call stack with function a
这次堆栈跟踪包括了带有函数a
的整个调用堆栈
Uncaught (in promise) Error: 343
at c (<anonymous>:6:9)
at a (<anonymous>:3:5)
I tested this in Chrome dev console.我在 Chrome 开发控制台中对此进行了测试。 I wonder what caused the difference and does this mean one should stick with async-await
for better debugbility?我想知道是什么导致了这种差异,这是否意味着应该坚持使用async-await
以获得更好的可调试性? Also are there any resources I can learn more about this difference?还有什么资源可以让我了解更多关于这种差异的信息吗?
This is expected.这是意料之中的。
In the then
version, the function a
has ran to completion before the then
callback executes.在then
版本中,函数a
在then
回调执行之前已经运行完成。 That anonymous callback is the only function on the call stack at that moment.该匿名回调是当时调用堆栈上的唯一函数。 When c
is called, and the rejection occurs, a
is not on the call stack.当调用c
并发生拒绝时, a
不在调用堆栈上。
In the await
version, the function a
is first suspended (it returns a promise), but then when b()
resolves, the execution context of a
is restored and execution of a
resumes.在await
版本中,函数a
首先被挂起(它返回一个 promise),但是当b()
解析时,a 的执行上下文被恢复并且a
的a
恢复。 So when the rejection occurs in c
, a
is on the call stack.因此,当c
中发生拒绝时, a
在调用堆栈上。
Its anonymous because its called inside an anonymous function: () => c()
.它是匿名的,因为它在匿名函数内部调用: () => c()
。 In the other example its called inside a
在另一个示例中,它在内部a
If you name your callback function, you will see the name inside the error log:如果您命名回调函数,您将在错误日志中看到名称:
const a = () => {
b().then(function test() {
c();
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.