Skip to content

Instantly share code, notes, and snippets.

@mistakster
Created April 6, 2017 10:00
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 mistakster/05da238b505011e70de490ac59822647 to your computer and use it in GitHub Desktop.
Save mistakster/05da238b505011e70de490ac59822647 to your computer and use it in GitHub Desktop.
A helper function which wrap any function expecting callback as the last argument and return promise
function toArray(obj) {
return [].slice.apply(obj);
}
module.exports = function promisify(fn) {
return function () {
const args = toArray(arguments);
const self = this;
return new Promise(function (resolve, reject) {
const fnArgs = args.concat(function (err) {
if (err) {
return reject(err);
}
const callbackArgs = toArray(arguments);
callbackArgs.shift();
resolve.apply(self, callbackArgs);
});
fn.apply(self, fnArgs);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment