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?
-
It seems like they shouldn't be parallel async events then unless I'm missing something. I would just do event1 -> event1 callback -> event2 -> event2 callback -> database insertonteria_– onteria_2011-05-21 20:46:51 +00:00Commented May 21, 2011 at 20:46
-
It is a request response ....parse the template-> render Page <- query the database.... I know that it is a bit trivial because parsing will always be quicker but it is a learning question.James– James2011-05-24 16:29:06 +00:00Commented May 24, 2011 at 16:29
Add a comment
|
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();
});
Comments
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.
1 Comment
James
I like the counter idea. So simple. Thank you.