1

I came accross to a problem where I can not understand how the order of the code is being executed. Let's say I have:

console.log("0");
foo();
console.log("1");

function foo(){
       console.log("2");
       jsonfile.readFile('test.json', function(err, obj){
            console.log("3");
       });
       console.log("4");
}

The output of the above program is "0 2 4 1 3" when I was expecting "0 2 3 4 1".

Why this is happening?

Marko Polo
  • 159
  • 8
  • 1
    Glad to see that you performed some rational logging and debugging. Not many people seem to do this. However, this gets asked every day. Given what you discovered on your own, it shouldn't be too hard to find multiple answers to this question. – llama Oct 07 '17 at 14:51

2 Answers2

3

readFile is asynchronous. The callback function will be called once the file has been read.

In the meantime, the rest of foo will finish running.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

jsonfile.readFile executes the callback function with the console.log("3") statement after the file has been read.

The console.log("4") statement aber jsonfile.readFile is executed right after the program has started reading the file, not after it has finished reading the file, as you may expect.

This is called asynchronous.

A lot of functionality in JavaScript and Node.js is based on this concept.

Here is a related question that has more info on how to deal with asynchronous function calls:

How do I return the response from an asynchronous call?

Patrick Hund
  • 19,163
  • 11
  • 66
  • 95