Archive for the ‘node.js’ Category

How to defer a callback’s execution in node.js

If you are new to node.js like me and finally got the understanding of how all the callback stuff works, then you may come into a situation when you want to write a function which does something and runs a callback passed in as parameter.

Such as in the code below:

var callback = function() {
    for (i = 0; i < 10; i++)
        console.log('callback', i);
};

var func = function(cb) {
    cb();
    console.log('func');
};

console.log('pre-func call');
func(callback);
console.log('post-func call');

However, you will notice that the output looks like the one below:

pre-func call
callback 0
callback 1
callback ...
func
post-func call

 

Well, this is something you actually do not want – you want your callback to get called asynchronously so that the code after cb(); gets processed prior to your callback call.

If such a case, modify the func function to look like this:

var func = function(cb) {
    process.nextTick(cb);
    console.log('func');
};

 

The process.nextTick() will defer your callback so that execution may continue. This time, the result will look like this:

pre-func call
func
post-func call
callback 0
callback 1
callback ...