Created
September 8, 2017 21:56
-
-
Save MiguelLattuada/e852f7b6f57edab4b5ca5e0001e5a9c7 to your computer and use it in GitHub Desktop.
Converts a Node.js-style callback API to a function that returns a Promise
This file contains hidden or 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
module.exports = function(fn, ctx) { | |
if (!fn || !(fn instanceof Function)) throw Error('Invalid arguments'); | |
return function() { | |
const _args = Array.from(arguments); | |
var promiseFn = function(resolve, reject) { | |
_args.push(function(err, data) { | |
if (err) return reject(err); | |
return resolve(data); | |
}); | |
fn.apply(ctx, _args); | |
}; | |
return new Promise(promiseFn); | |
}; | |
} |
Author
MiguelLattuada
commented
Sep 11, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment