Skip to content

Instantly share code, notes, and snippets.

@bengl
Created June 12, 2014 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bengl/0197e27dabb341538b38 to your computer and use it in GitHub Desktop.
Save bengl/0197e27dabb341538b38 to your computer and use it in GitHub Desktop.
Promisify if it calls a callback, pass through if it returns a promise.
// non-`Promise.defer()` version of https://github.com/petkaantonov/bluebird/issues/159#issuecomment-38348877
var Promise = require('bluebird');
function maybePromisify(fn, ctx){
return function() {
var args = Array.prototype.slice.call(arguments);
return new Promise(function(fulfill, reject){
args.push(function(err, result){
if (err)
reject(err);
else
fulfill(result);
});
var p = fn.apply(ctx, args);
if (p && typeof p.then === 'function')
fulfill(p);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment