Skip to content

Instantly share code, notes, and snippets.

@cvan
Last active June 23, 2017 14:02
Show Gist options
  • Select an option

  • Save cvan/8f649c995f93b0187432 to your computer and use it in GitHub Desktop.

Select an option

Save cvan/8f649c995f93b0187432 to your computer and use it in GitHub Desktop.
turn any callback function into a promise-based one
var Promise = require('es6-promise').Promise;
function promisify(func) {
// Already a Promise.
if (func && typeof func.then === 'function') {
return func;
}
return function () {
var args = Array.prototype.slice.apply(arguments);
return new Promise(function (resolve, reject) {
func.apply(this, args.concat(function (err, value) {
if (err) {
reject(err);
} else {
resolve(value);
}
}));
});
};
}
/*
Sample usage:
var Joi = require('joi'); // Using a library whose methods are promises.
var validate = promisify(Joi.validate); // Wraps `Joi.validate` in a promise.
or
var phantom = require('node-phantom-simple');
phantom.create = utils.promisify(phantom.create);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment