Revealing Module Pattern and Promises

If you're classes are creating immutable objects, for example using the revealing module pattern described at this site, you'll notice that you're unable to use Promise.promisifyAll() on the object (quite rightly) as it can't mutate the frozen object to add the Async methods.

Solution

The solution below is a simple application, using two immutable objects, and using bluebird to handle the promises.

CLASS: APP1

'use strict';
var Promises = require('bluebird');

var App = function() {
  var self = {};
  self.addFive = function(value, callback) {
    callback(null, value + 5);
  };
  Promises.promisifyAll(self);
  return Object.freeze(self);
};

module.exports = App;

CLASS: APP2

'use strict';
var Promises = require('bluebird');

var App2 = function() {
  var self = {};
  self.addTen = function(value, callback) {
    callback(null, value + 10);
  };
  Promises.promisifyAll(self);
  return Object.freeze(self);
};

module.exports = App2;

The general idea here is that you use promisfyAll internally to the object and freeze after that point. Naturally, write a test to make sure this works:

TEST SUITE:

'use strict';
var App = require('../lib/app1');
var App2 = require('../lib/app2');

describe('promiseTest', function() {
  it('Should be promised', function(done) {
    var app = new App();
    var app2 = new App2();
    app
      .addFiveAsync(0)
      .then(function(val) {
        app2
          .addTenAsync(val)
          .then(function(newVal) {
            assert.equal(newVal, 15);
          });
      })
      .then(function() {
        done();
      });
  });
});