Waiting for two (or more) events

337 views
Skip to first unread message

Serge in Darkness

unread,
Jan 28, 2010, 11:50:37 AM1/28/10
to nodejs
What is most convenient way to wait for two events? Let's say I'm
waiting for POST body response "complete" event AND opening Tokyo
Tyrant connection at the same time (waiting for callback). How can I
do something only when both conditions are met? Do I have to use some
sort of external semaphore (first approach I thought about) or it can
be done in different way?

Tim Caswell

unread,
Jan 28, 2010, 12:09:55 PM1/28/10
to nod...@googlegroups.com
I don't think there is a built in way to do this. Maybe there is something I missed in the promise api change that's been going on though.

Here is a simple library that may help:

// combo library
function Combo(callback) {
this.callback = callback;
this.items = 0;
this.results = [];
}
Combo.prototype = {
add: function () {
var self = this;
this.items++;
return function () {
self.check(self.items - 1, arguments);
};
},
check: function (id, arguments) {
this.results[id] = arguments;
this.items--;
if (this.items == 0) {
this.callback.apply(this, this.results);
}
}
};

// Usage
var both = new Combo(function () {
puts(inspect(arguments));
});
setTimeout(both.add(), 100);
setTimeout(both.add(), 50);

For use with node promises, you would simply pass `both.add()` to the addCallback functions. When everything is done, your initial callback will be called with the results ordered in the order you registered them, not the order they actually came.

> --
> You received this message because you are subscribed to the Google Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com.
> To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.
>

Reply all
Reply to author
Forward
0 new messages