Skip to content

Instantly share code, notes, and snippets.

@yanatan16
Last active September 23, 2018 22:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yanatan16/8216252 to your computer and use it in GitHub Desktop.
Save yanatan16/8216252 to your computer and use it in GitHub Desktop.
Wrapping a callback-based function into an ES6 Generator (requires node 0.11+)
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