-
-
Save eiriklv/8b71708d40aeb2c5ce22 to your computer and use it in GitHub Desktop.
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
| var q = require('q') | |
| function generatorify(fn, context) { | |
| return function() { | |
| var deferred = q.defer(), | |
| callback = makeCallback(deferred), | |
| args = Array.prototype.slice.call(arguments).concat(callback); | |
| fn.apply(context, args); | |
| return deferred.promise; | |
| }; | |
| } | |
| function makeCallback(deferred) { | |
| return function (err) { | |
| if (err) { | |
| deferred.reject(err); | |
| } else if (arguments.length < 2) { | |
| deferred.resolve(); | |
| } else if (arguments.length === 2) { | |
| deferred.resolve(arguments[1]); | |
| } else { | |
| deferred.resolve(Array.prototype.slice.call(arguments, 1)); | |
| } | |
| }; | |
| } | |
| // This is monkey patching so don't do it lightly | |
| Function.prototype.generator = function (context) { | |
| return generatorify(this, context); | |
| }; | |
| /// Usage | |
| function callbackBasedFunction(arg, callback) { | |
| callback(null, arg + 1); | |
| } | |
| function *generator() { | |
| var genFunction = generatorify(callbackBasedFunction); | |
| result = yield genFunction(2); | |
| assert result == 3; | |
| // or with monkey patching | |
| result = yield callbackBasedFunction.generator(null)(2) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment