Nodejs & Promise : advanced tips – part two – Using Promise ? Yes, but just any one ;-)

This is the second part of my series dedicated to promise. The previous post, about anti-pattern, is here.

♻ The problem

Let’s say you find a module that fit your need. It returns Q promise while your program use Bluebird promise. Oups… . It probably work, but I’m keen on mixing Pormise implementation, and on being forced to use an implementation I don’t want.

A module should not force the use of a specific kind of promise

♻ A first solution:

Some libraries let users to plug in their favorite promise. Here is an example extract from mongoose documentation:

// Use native promises
mongoose.Promise = global.Promise;
assert.equal(query.exec().constructor, global.Promise);

// Use bluebird
mongoose.Promise = require('bluebird');
assert.equal(query.exec().constructor, require('bluebird'));

This works, but having to plug in a promise for each module (each module having it’s own way to define Promise) is cumbersome.

♻ A better solution: Any-promise.

Here is how any-promise introduces itself:

Let your library support any ES 2015 (ES6) compatible Promise and leave the choice to application authors. The application can optionally register its preferred Promise implementation and it will be exported when requiring any-promise from library code.

The code of the module is straightforward: it get a Promise class from any-promise:

const Promise = require('any-promise');
new Promise(function(resolve, reject){...});

The application then as to register the implementation he wants to use before using any-promise or any mobule depending on it:


Note that any-promise won’t accept to register multiple implementations.

♻ Usage

Numerous modules already depends on any-promise. I regularly use mzthenify-all and fs-promise along with Bluebird. You can also have a look to my own module: events-to-any-promise.

This conclue my posts about Promise. I hope you’ll think to it when you’ll write your public module.

See you and have a nice code 🙋