MathieuTurcotte / node-wait

WaitForAll and WaitForAny on EventEmitter.
MIT License
10 stars 2 forks source link

"Early" listeners #5

Closed mathieumg closed 8 years ago

mathieumg commented 9 years ago

I've been using waitForAll for a while in multiple situations, thank you for this convenient wrapper. I was wondering, would you be open to a PR that allows waitForAll to start listening to emitters as soon as they're added?

My current problem is that I have an eventA that triggers an eventC, and an eventD that is triggered both by the eventA and an eventB. I want to be able to know when eventC and eventD have happened but I have no right moment to start listening to them. If I start listening for eventC as soon as eventA happens, I don't have an handle on the listener for eventD yet and if I wait for both eventA and eventB to happen before listening to eventC and eventD, I might miss eventC altogether.

If waitForAll would listen (probably through an option?) for events as soon as they're added and keep track of which have happened, a call to .wait() would be able to callback properly immediately if it knows the events have already been fired. What do you think?

Thank you.

MathieuTurcotte commented 9 years ago

Without knowing the specifics of your problem, it feels like you have some initialization problem. Events may not be the best fit for your situation. Have you considered mapping those events to promises and doing something like goog.Promise.firstFulfilled or whatever the equivalent would be for the library you're using.

http://google.github.io/closure-library/api/source/closure/goog/promise/promise.js.src.html#l462

When writing the library, I intentionally made the point at which listening starts explicit to avoid confusion around initialization and to keep the implementation and contract simple. One thing which could be added is a cancel API to abort the wait call. In your case, this would let you create a new wait for all after the first batch of events have fired. Would something like that accommodate your needs?

mathieumg commented 8 years ago

Sorry for the very late reply! I switched to using native promises pretty heavily and, as you said, they're a better fit than event emitters/listeners for this kind of situation.