Jacob
Jacob

Reputation: 420

how callback function in nodejs is working?

I have a sample code and outputs are as below: code:

for(var i = 0; i <20; i++) {
    var fs = require("fs");

    fs.readFile('input2.txt', function (err, data) {
        if (err) return console.error(err);
        console.log("first started\n");
        console.log(data.toString());
    });

    console.log("first Ended");

    console.log("second started");
    var data = fs.readFileSync('input1.txt');

    console.log(data.toString());
    console.log("second Ended");
}

Output:

first Ended second started second Ended first Ended second started and so on till 20 times first started
1 first started 1 and so on till 20 times

As input2.txt has just one character in it and input1.txt has no of lines in it. I was assuming that callback function would be invoked after printing input from 1st file after one iteration as the file read operation should be completed by that time. But its not the case. Means it is completing sync operation first then only callback is getting work. How would that be possible? If callback has to wait for so long, what is the purpose of asynchronous call here?

Upvotes: 0

Views: 73

Answers (2)

jfriend00
jfriend00

Reputation: 707218

Your for loop runs synchronously to completion and starts 20 fs.readFile() operations which are all asynchronous (meaning they will finish later).

Then, after the for loop finishes, the asynchronous operations will start to finish and get served one by one (not necessarily in the order they were started in).

Because your own Javascript in node.js is single threaded, that means your current thread of execution runs to completion so the for loop runs until it is done. Each iteration of the for loop starts a fs.readFile() operation which is asynchronous. That operation then runs in the background while your for loop continues. As each fs.readFile() operation completes, its callback is added to the JS event queue. When your current thread of execution finishes (and only then), the Javascript interpreter will pull the first item out of the event queue and run it (if there's anything in the event queue at that point). If there's nothing in the event queue at that point (because none of the asynchronous operations have yet completed, then the JS engine will wait for the next event to occur and when the first async operation completes and puts a callback into the event queue, then the JS engine will service that event and call that callback.

Asynchronous callbacks like this are never called in the middle of a piece of Javascript executing. JS is single threaded so these async callbacks won't be called until the current thread of JS finishes.

Though this answer was written for Ajax calls in the browser, the event queue concept is the same in node.js so this might also help explain: How does JavaScript handle AJAX responses in the background?

Upvotes: 1

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9406

When a function named async, its callback called in next tick in node.js

In your snippet, all statements in loop called in current tick and executed. But that callback to read file async, puts in next tick queue to be execute.

Please look at Process.nextTick

Upvotes: 0

Related Questions