Promisified events using the Façade pattern

Scenario:

Andrei Cacio
FineCoding
2 min readApr 26, 2018

--

You have a reusable module. Under the hood it uses some kind of event driven architecture. We wish to expose a public API with which we can use our inclosed module. The tricky part with having events is that we are dealing with async behavior. It is not a simple function which we can export and simply use. Also we don’t want to expose the event bus or any information regarding our internal implementation.

First let’s look at what the Facade pattern offers:

The Façade pattern provides an interface which shields clients from complex functionality in one or more subsystems. It is a simple pattern that may seem trivial but it is powerful and extremely useful […]

This is exactly what we want. To keep our private implementation, well private, and expose a more generic interface for others to use.

Example

Say we have an auth module. A simple eventemitter2 based event bus would look like so:

And a simple authentication flow would look like so:

We would like to expose an authenticate(user, pass) generic function without leaking internal logic. So here is how our facade will look like:

Notice that for this pattern to work, the line order matters. We first need to attach the success/fail handlers before we emit the auth action. With the handlers in place, we can be sure that our returned promise will resolve/reject properly based on the incoming events.

This looks good, however there is a slight problem. Have you noticed it? We introduced a tiny memory leak. Every time we will call the authenticate method, another couple of listeners will register on our main bus and on the second call it will repeat. This means that on every success or fail trigger, the handlers will keep executing.

To solve this issue, eventemitter2 has a special method called once which will dispose the handler as soon as it is triggered.

And our final public method will look like so:

Conclusion

I found this approach quite helpful for keeping a module’s API clean and simple. Also with this pattern we isolate the internal implementation from the outside world. Even though we are using an event emitter we can at any time change it with another implementation and the API won’t suffer.

Bibliography:

  1. [Facade Pattern] http://www.dofactory.com/javascript/facade-design-pattern
  2. [eventemitter2] https://github.com/EventEmitter2/EventEmitter2
  3. [Mastering JavaScript Design Patterns] https://www.amazon.com/Mastering-JavaScript-Design-Patterns-Simon/dp/1783987987

--

--

Andrei Cacio
FineCoding

JavaScript Developer @ Evozon | proud speaker and co-organizer at JSHeroes Community Meetups #javascript #web