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 ...
Advertisements

One response to this post.

  1. As far as everyone as being a member at this point, I just didnt actually realize that I got an affiliate the following. If your post was shared I gotten a announcement, to ensure that I could truthfully attend Comments, thus perhaps which is them. Yet we’re certainly all participants in the wonderful world of thoughts.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: