Onnables

Yoshua Wuyts
1 min readMar 24, 2015

--

Lately I’ve been working a lot with ES6 promises. Whereas at first they seemed pretty unintuitive, I’m starting to see how they can be useful. In order to be used inside of a Promise chain, all a value has to do is expose a .then() function. If a value doesn’t have a .then() present, ES6 promises cast them to a Promise anyway, but that’s beside the point here.

What is interesting is the fact that by having a common interface, any function can pretend to be a Promise and play ball with them.

Node streams work in the same way by exposing a .pipe() function. Arrays have .map() (mappables) and generators have the .next() function that calls the next yield.

There’s one that I’ve been missing in this list, and that is the common interface of events. In Node events always expose a .on() and .then() function. Just like .then(), these .on() calls can be infinitely chained. I shall name them (a brief moment of silence for horrible naming) onnables.

Events are neat, objects shouldn’t be afraid to have more listeners as they are super super cheap (compared to observers, which are expensive by design, to the dismay of many). By recognizing this common interface, it might be easier to create modules that can consume these onnables and do interesting things with them, no matter what they actually do. A bit like with Promises and their thennables.

And that concludes my Tuesday-evening brainfart, time for me to slowly slither back to preparing a presentation.

Originally published at github.com on March 24, 2015.

--

--