开发者

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 tha开发者_如何学Ct 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?


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();
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜