Last active
December 21, 2016 02:17
-
-
Save devsnek/121e5b3a7aba4481a90a7a410a3550e0 to your computer and use it in GitHub Desktop.
with all this hype surrounding promisifying callbacks, i thought i would spice things up, and offer a function that callbackifies promises.
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 callbackify (promise) { | |
return function execute() { | |
const callback = arguments[arguments.length - 1]; | |
const args = Array.prototype.slice.call(arguments, 0, arguments.length - 1); | |
if (promise instanceof Promise) promise.then(r => callback(null, r)).catch(callback); | |
else if (typeof promise === 'function') promise(...args).then(r => callback(null, r)).catch(callback); | |
else throw new TypeError('`promise` must be a Promise or Function which returns a Promise!'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment