Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS node asynchronous handling of events

Can some one point me to or explain some kind of event based design pattern that handles the situation of waiting on two events to complete to perform an action.
I have a template that is loaded async and a database call that is also happening at the same time. I have a response that needs to be executed only when both of these tasks has completed.
The only solution I can come up with is doing something ugly like putting in booleans that set to true on the event finish and then check to see if they are all true. Is there a better way to do this?

like image 991
James Andino Avatar asked May 21 '11 20:05

James Andino


2 Answers

Just to add an example of either from Chris' answer:

Using async, https://github.com/caolan/async

async.parallel([
    function(callback){
        // query a database, lets say mongodb/mongoose
        User.findOne({email: email}, function(err, user){
            callback(err, user);
        });
    },
    function(callback){
        // Load a template from disk
        fs.readFile('views/user.html', function (err, data) {
            callback(err, data)
        });
    }
], function(err, results){
    // Should have [user, template data]
});

Or with counters:

var user     = false,
    template = false,
    count    = 2;

function build_user_view(){
    // user, template should be available
}

User.findOne({email: email}, function(err, userDoc){
    user = userDoc;
    --count || build_user_view();
});


fs.readFile('views/user.html', function (err, data) {
    template = data;
    --count || build_user_view();
});
like image 56
Josh Avatar answered Sep 18 '22 16:09

Josh


There's no simple way to do this really, but there are lots of flow control libraries that handle this sort of thing. The simplest way might be to keep a global counter that increments when you start an async call, then decrements in the callback when it finishes. Each operation could check the counter when it finishes, and if it's zero trigger the response that depends on both being completed.

like image 38
Chris Fulstow Avatar answered Sep 21 '22 16:09

Chris Fulstow