Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging inside asynchronous callbacks

I have the following code:

...
fs.readdir('mydir', function(error, files)
{
  for(var i = 0; i < files.length; i++)
  {
    console.log(files[i]);
  }
});
...

When I try to debug the code inside my callback function, the debugger just skips over the callback and only executes code before and after (in the ellipses). Is there a special flag that I need to set to be able to debug asynchronous code?

I have verified that the callback runs because I am getting output of the file names.

like image 979
user3285713 Avatar asked Jan 20 '26 16:01

user3285713


1 Answers

You set a breakpoint inside the callback and run to that breakpoint. Asynchronous callbacks do not execute sequentially (they execute some indeterminate time in the future) so you can't step through them line by line and get into the callback.


To refresh your memory, if you had this code:

console.log("a");
fs.readdir('mydir', function(error, files) {
  for(var i = 0; i < files.length; i++)  {
    console.log("file #: " + i);
  }
});
console.log("b");
console.log("c");

What you would see in the log would be:

a
b
c
file #: 1
file #: 2
file #: 3
file #: 4

Because the async callback is called some indeterminate time later after the rest of your JS thread of execution has finished. There is no sequential execution from top to bottom that includes the callback and thus the debugger will not "step through" the callback on its own as you execute line by line.

So, instead you tell the debugger that you'd like it to stop whenever execution gets to the callback by setting a breakpoint there. Then, you run the code and when execution gets to the callback, your breakpoint will break into the debugger and you then step through the execution of that call of the callback.

like image 191
jfriend00 Avatar answered Jan 23 '26 04:01

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!