Skip to content

Instantly share code, notes, and snippets.

@m1sta
Created May 27, 2015 19:28
Show Gist options
  • Save m1sta/6510668759ee42a647f0 to your computer and use it in GitHub Desktop.
Save m1sta/6510668759ee42a647f0 to your computer and use it in GitHub Desktop.
Utility function to convert a function with signature fn(args, cb(err, result)) to return a promise
//Utility function to convert a function with signature fn(args, cb(err, result)) to return a promise
function promisify ( fn, context ) {
return function () {
var args = [].slice.call( arguments );
return new Promise( function ( fulfil, reject ) {
var callback = function ( err ) {
if ( err ) return reject( err );
fulfil.apply( null, [].slice.call( arguments, 1 ) );
};
args.push( callback );
fn.apply( context, args );
});
};
};
@m1sta
Copy link
Author

m1sta commented May 27, 2015

Example...

var hello = function(msg, cb){cb(null, "Hello from " + msg)}
var result = await promisify(myFn)(arg1, arg2, arg3)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment