hub.js
hub.js copied to clipboard
Execute listeners in parallel?
Hello,
I've been using your library for a year and a half and been very pleased so far. Good work!
In the newest version, is there a way to execute two or more listeners in parallel instead of the deterministic, sequential order noted in the documentation? To give an example use case, two caches may listen on a get event and whichever returns first is returned to the emitter. Both cache gets are async so executing them sequentially will be quite slow.
If this feature is present, could you update the documentation? If not, please consider this a feature request. (I think this feature was in previous versions of your code?)
Thanks, Edwin
Thanks for getting in touch.
To clarify things: The call order of the listeners is predictable and a second listener on the same event name will be called immediately regardless of the first one invoking it's callback. Therefore execution does happen in parallel.
Your issue seems to be that hub.js waits for all the callbacks to be invoked before returning. By default it will return the value of the second listener, regardless of callback invocation order.
A possible implementation of the feature could be used like this:
hub.emit({
event: 'multiple.things',
firstResult: true
}, function (err, result) { /* ... */ });
Is that what you need?
Ah I see. Then I have two requests:
- Make it clearer in the documentation that execution happens in parallel.
- Provide an option for hub.js to instead of waiting for all callbacks to be invoked before returning, to just wait until the one that returns soonest is invoked before returning. (Trying to disambiguate between "first result" and "temporally soonest", which are different.)
Yes, agreed. We have to think about a better name for the option that expresses "soonest" somehow.
Could you help out on the documentation? It's in the docs
folder.
Here are some first thoughts:
-
fastestResponse
-
firstReturn
One question: What would you expect to happen in case of an error? One solution would be to wait for the first non-error response. Or should it respond with an error in that case?
I guess there are a few cases:
- (default) Wait until all handlers return
- Return on first response (could be either success or error)
- Return on first error
- Return on first success
You could make a strategy option where you can specify one of the four.
On Tue, Nov 5, 2013 at 3:15 AM, Maximilian Antoni [email protected]:
Here are some first thoughts:
- fastestResponse
- firstReturn
One question: What would you expect to happen in case of an error? One solution would be to wait for the first non-error response. Or should it respond with an error in that case?
— Reply to this email directly or view it on GitHubhttps://github.com/mantoni/hub.js/issues/3#issuecomment-27713568 .
Good point. :+1: