Doctor Doctor - 2 months ago 5
Node.js Question

node js callback - Will the order always be the same?

I wrote the following function that takes a callback. I always thought that the content of a callback might be executed later. In this case it doesn't...

doesSomething(function(){
console.log("1");
var i = 0;
while (i < 10000)
{
console.log("hello");
i = i + 1;
}
});
console.log("2");
console.log("3");


Whatever I do, "2" and "3" always comes after "1" and a thousand of "hello".
Like this:

1

hello

hello

...

hello

hello

2

3


What I thought it would do:

2

3

1

hello

hello

...

hello

hello


Even if this behaviour makes my life simpler I don't really understand why the execution is procedural.

Do you think that in some case it might go reverse ?

Answer

javascript is a single threaded language, but not the node.js runtime or the browser. There are certain functions provided by node.js or the browser that would trigger for a function to be assigned to a task queue to be processed in a separate thread

lets take your example and make dosomething async

this is your synchronous code that would print, 1 hello...,2,3

function doesSomething(callback) {
    callback();
}
doesSomething(function(){
    console.log("1");
    var i = 0;
    while (i < 3)
    {
        console.log("hello");
        i = i + 1;
    }
});
console.log("2");
console.log("3");

and this is the async code, that prints out 3, 2, 1, hello ...

function doesSomething(callback) {
    setTimeout(callback, 0);
}

doesSomething(function(){
    console.log("1");
    var i = 0;
    while (i < 3)
    {
        console.log("hello");
        i = i + 1;
    }
});
console.log("2");
console.log("3");

to explain why the second code is async, you have to understand that setTimeout is not part of javascript, its an api provided by node.js and the browsers. setTimeout puts the callback function into a queue to be processed. At this time a separate thread runs the setTimeout and when the timer ends it puts the callback into a callback queue, and when the call stack is clear, whatever is in the callback queue will be moved to the call stack and processed.

in node you can use process.nextTick(yourFunction); to make it async, this is just another function that nodejs provides you which is better than using setTimeout (which I wont get into here) you can checkout https://howtonode.org/understanding-process-next-tick to understand more about process.nextTick

for more info check out this video https://youtu.be/8aGhZQkoFbQ?t=19m25s

Comments