I have the following snippet implemented with 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
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:
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
Uncaught (in promise) Error: 343
at c (<anonymous>:6:9)
at a (<anonymous>:3:5)
I tested this in Chrome dev console. I wonder what caused the difference and does this mean one should stick with async-await
for better debugbility? Also are there any resources I can learn more about this difference?
CodePudding user response:
This is expected.
In the then
version, the function a
has ran to completion before the then
callback executes. 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.
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. So when the rejection occurs in c
, a
is on the call stack.
CodePudding user response:
Its anonymous because its called inside an anonymous function: () => c()
. In the other example its called inside a
If you name your callback function, you will see the name inside the error log:
const a = () => {
b().then(function test() {
c();
});
};