Why Do I Lose Stack Trace When Using Async-await In Node.js?
Solution 1:
Because in the first code, everything up until the Error
is on the same tick of the event loop.
Before an asynchronous callback, the one from setTimeout
, can enter the call stack (The stack trace is built from it), the call stack must be empty.
So since the first code runs everything synchronous until the Error
call, all those calls are in the call stack. But on the second approach, the Error
is called after await
ing a setTimeout
call. When the setTimeout
is done. The event loop puts the callback back into the stack, for this, the call stack must be empty.
So now, you don't have functionTwo
& functionThree
on the call stack, that's why they don't appear.
The stack trace is the state of the stack when the error ocurred.
Here's a rough interpretation of what happens with the stack in both codes:
First Code
1) functionThree is pushed into the stack
2) functionTwo is pushed into the stack
3) functionOne is pushed into the stack
4) Erroris thrown
Second Code
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 eventloop1) setTimeout callback is called
2) Erroris thrown
I recommend watching this video to understand how all of this works:
What the heck is the event loop anyway by Philip Roberts
On the newests versions of Node.js you can use --async-stack-traces
flag to have an improved stack trace when working with asynchronous code.
You can read a little bit more about this at https://v8.dev/blog/fast-async
Post a Comment for "Why Do I Lose Stack Trace When Using Async-await In Node.js?"