Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js async.js nextTick vs setImmediate

I have a large node.js application that heavily uses the async.js module.

I have a lot of code like this:

async.series([
    function(callback){
        sql.update(query, callback);
    },
    function(callback){
        if (something){
            sql.update(query2, callback);
        }
        else{
            callback(null);
        }
    }

]);

The big problem is the synchronous callback in the else statement. I read a while back that you should not do that with async.js as it could cause unexpected results, but I'm not sure what the best alternative is. I read that I should use process.nextTick in some places, but now I'm reading that we should not use that and it should be setImmediate.

Can someone point me in the right direction? Thanks!

like image 426
Christie Avatar asked Mar 19 '14 18:03

Christie


1 Answers

I FINALLY found the reference I remember reading a while back.

It is on this page: http://caolanmcmahon.com/posts/nodejs_style_and_structure/

He discusses the general case in rule #3 and in more direct correlation to my issue in response to the first comment on the page.

Even if it's not the cause of my random error, I would like to use the module according to the author's intentions which was the point of the question.

In this article, he mentions using process.nextTick, but I really think node is trying to move away from that in this case and I found a response in a async issue thread from a month ago that says:

"You need to make sure your functions are running asynchronously - if you don't know whether it'll be asynchronous or not you can force it to be async using setImmediate"

So, that's the answer I'm going with. I'm going to wrap any synch callbacks in setImmediate.

like image 168
Christie Avatar answered Oct 08 '22 03:10

Christie