Waiting for two (or more) events

344 vues
Accéder directement au premier message non lu

Serge in Darkness

non lue,
28 janv. 2010, 11:50:3728/01/2010
à 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

non lue,
28 janv. 2010, 12:09:5528/01/2010
à 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.
>

Répondre à tous
Répondre à l'auteur
Transférer
0 nouveau message