Created
April 6, 2017 10:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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