Search code examples
javascripteventspromisepublish-subscribe

One time event handling using promises?


Pretty much usual scenario. I want to have some decoupled piece of code, that is triggering event when something is ready. This will happen only once for the whole application run.

On other side, there is another piece of code, where I want something else to happen when two or more events are triggered. I mean like all of them, like dependencies.

Alright, more async things together ... definitely promises right ?

Then I started thinking. Is it really wise to use pub/sub for one time events ? Wouldn't be better to just make accessible promise, that resolves once that event is about to be triggered ? However that would mean I need to kinda interconnect that decoupled code. One thing is having shared EventEmitter, but being dependent on some code to actually create promise ... that sounds rather bad.

So I am thinking about some kind of mix. Having module, where other modules can ask for "event" by it's name and obtaining prepared Promise object. Other module should then trigger that event and effectively fulfilling/rejecting that event this way.

var promisedLand = require('./promisedLand');
promisedLand.waitFor('event'); // returns promise
promisedLand.resolve('event', value);
promisedLand.reject('event', error);

What do you think about this solution ? Any chance there is some solution like this already available ?


Solution

  • Alright, I have made my own solution similar to the one presented in the question.

    Welcome to the Promised Land