Tushar Nikam
Tushar Nikam

Reputation: 624

Node JS callbacks executing in sychronously

I have this code in node js

var PrintFirstName = function(first_name , cb) {
    cb("First name  is "+first_name) ;
}
PrintFirstName("Tushar" , function(res){
    for(var i = 0 ; i < 100000; i++) {
        console.log(i);
    }    
    console.log("processing callback");
});
console.log("Code continue....") ;

As callbacks are asynchronous in nature , my expected order of execution should be Code continue , numbers 1-10000 and then processing callbacks

But if i run the above i am getting output as numbers 1-10000 , processing callbacks and then Code continue . Code continue should be executed first.Why it is waiting for callbacks to complete.

Upvotes: 1

Views: 52

Answers (1)

Mihai Popescu
Mihai Popescu

Reputation: 396

The code you wrote is not asynchronous, usually async functions in javascript requires constructing the expression argument to setTimeout or setInterval manually.

In your case:

var PrintFirstName = function(first_name , cb) {
    cb("First name  is "+first_name) ;
}

PrintFirstName("Tushar" , function(res){
        for(var i = 0 ; i < 100000; i++) {
            console.log(i);
        }    
 setTimeout(function() {        console.log("processing callback");}, 0);
});

console.log("Code continue....") ;

But keep in mind that this will not work when making calls on Object methods

Take a look here http://devedge.primedirective.net/toolbox/examples/2003/CCallWrapper/index.html

Upvotes: 1

Related Questions