Last active
August 29, 2015 14:09
-
-
Save redgeoff/f8a1703809fa29708dbe to your computer and use it in GitHub Desktop.
Promisify
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
| // This implmentation is probably very similar to Promise.promisify--it can be helpful to visualize the details separately | |
| var promisify = function (fn, thisArg) { | |
| return function () { | |
| var args = Array.prototype.slice.call(arguments, 0); // convert to array | |
| return new Promise(function (resolve, reject) { | |
| var callback = function () { | |
| var err = arguments[0]; | |
| if (err) { | |
| reject(err); | |
| } else if (arguments.length <= 2) { | |
| resolve(arguments[1]); | |
| } else { | |
| var args = Array.prototype.slice.call(arguments, 0); // convert to array | |
| args.splice(0, 1); // remove err arg | |
| resolve(args); | |
| } | |
| }; | |
| args.push(callback); | |
| fn.apply(thisArg, args); | |
| }); | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment