Created
October 15, 2015 02:59
-
-
Save okorz001/aeeb3e2496ac1f3aa581 to your computer and use it in GitHub Desktop.
Convert function with node style callback into a one that returns a 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
var slice = Array.prototype.slice; | |
function promisify(f) { | |
return function() { | |
// Save arguments and promote to real Array. | |
var args = slice.call(arguments); | |
return new Promise(function(resolve, reject) { | |
// Add our callback to argument list. | |
args.push(function(err, result) { | |
if (err) { | |
reject(err); | |
} | |
else if (arguments.length == 2) { | |
resolve(result); | |
} | |
else { | |
// Promises are fulfilled with a single value, so pack all | |
// arguments into an Array (except the undefined error). | |
var results = slice.call(arguments, 1); | |
resolve(results); | |
} | |
}) | |
f.apply(f, args); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment