Skip to content

Instantly share code, notes, and snippets.

@okorz001
Created October 15, 2015 02:59
Show Gist options
  • Save okorz001/aeeb3e2496ac1f3aa581 to your computer and use it in GitHub Desktop.
Save okorz001/aeeb3e2496ac1f3aa581 to your computer and use it in GitHub Desktop.
Convert function with node style callback into a one that returns a Promise
var slice = Array.prototype.slice;
function promisify(f) {
return function() {
// Save arguments and promote to real Array.
var args = slice.call(arguments);
return new Promise(function(resolve, reject) {
// Add our callback to argument list.
args.push(function(err, result) {
if (err) {
reject(err);
}
else if (arguments.length == 2) {
resolve(result);
}
else {
// Promises are fulfilled with a single value, so pack all
// arguments into an Array (except the undefined error).
var results = slice.call(arguments, 1);
resolve(results);
}
})
f.apply(f, args);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment