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?

asked Oct 7, 2017 at 14:44
1
  • 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. Commented Oct 7, 2017 at 14:51

2 Answers 2

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.

answered Oct 7, 2017 at 14:46
Sign up to request clarification or add additional context in comments.

Comments

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?

answered Oct 7, 2017 at 14:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.