Skip to content

Instantly share code, notes, and snippets.

@redgeoff
Last active August 29, 2015 14:09
Show Gist options
  • Save redgeoff/f8a1703809fa29708dbe to your computer and use it in GitHub Desktop.
Save redgeoff/f8a1703809fa29708dbe to your computer and use it in GitHub Desktop.
Promisify
// This implmentation is probably very similar to Promise.promisify--it can be helpful to visualize the details separately
var promisify = function (fn, thisArg) {
return function () {
var args = Array.prototype.slice.call(arguments, 0); // convert to array
return new Promise(function (resolve, reject) {
var callback = function () {
var err = arguments[0];
if (err) {
reject(err);
} else if (arguments.length <= 2) {
resolve(arguments[1]);
} else {
var args = Array.prototype.slice.call(arguments, 0); // convert to array
args.splice(0, 1); // remove err arg
resolve(args);
}
};
args.push(callback);
fn.apply(thisArg, args);
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment