Skip to content

Instantly share code, notes, and snippets.

@jakemcgraw
Last active February 24, 2016 20:18
Show Gist options
  • Select an option

  • Save jakemcgraw/db3b3bbd601499931f50 to your computer and use it in GitHub Desktop.

Select an option

Save jakemcgraw/db3b3bbd601499931f50 to your computer and use it in GitHub Desktop.
Pattern for blue compatible modules
modules.export = (function(){
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
return function(params, cb) {
return fs.doSomeStuffAsync(params)
.then(function(result){
return someOtherAsync(result);
})
.then(function(moreResults){
return someMoreAsync(moreResults);
})
.finally(cb || function(){ });
};
})();
@traviskaufman
Copy link
Copy Markdown

This looks real good! I think usually the client worries about error handling, and Bluebird.prototype.asCallback is your friend here! :)

/* promise-fn.js */
'use strict';

// I like calling bluebird Bluebird because otherwise it clobbers global.Promise in newer versions of v8 / ES2015.
var Bluebird = require('bluebird');
var fs = require('fs');

Bromise.promisifyAll(fs);

module.exports = function(params, cb) {
  return fs.doSomeStuffAsync(param)
    .then(function(result) {
      return someOtherAsync(result);
    })
    .then(function(moreResults) {
      return someMoreAsync(moreResults);
    })
    .asCallback(cb);
};

Now it can be consumed like

/* index.js */
'use strict';

var Bluebird = require('bluebird');
var promiseFn = require('./promise-fn');

// A promise that can be caught
promiseFn({ foo: 'derp' }).catch(console.error.bind(console));

// A promise that can be chained
promiseFn({foo: 1}).then(function(results) {
  console.info('peep these results ====>', results);
}).catch(console.error.bind(console));

// Something that can be used with a callback
promiseFn({foo: 1}, function(err, results) {
  if (err) return console.error(err);
  console.info(results);
});

@jakemcgraw
Copy link
Copy Markdown
Author

Thanks for advice! Working it in now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment