Skip to content

Instantly share code, notes, and snippets.

@davidchase
Last active August 29, 2015 14:07
Show Gist options
  • Save davidchase/bd743b4e0d02f46ceb4e to your computer and use it in GitHub Desktop.
Save davidchase/bd743b4e0d02f46ceb4e to your computer and use it in GitHub Desktop.
Async with generators
// Tackling async events without
// callbacks using es6 generators
// http://kangax.github.io/compat-table/es6/#generators_(yield)
var async = function(parameters, callback) {
setTimeout(function() {
callback(parameters);
}, 1000);
};
var currier = function(fn) {
var args = Array.apply(null, arguments);
args.shift()
return function() {
return fn.apply(this, args.concat(Array.apply(null, arguments)));
};
}
var coroutine = function(generator) {
var iterator;
iterator = generator();
var foward = function(response) {
var state;
state = iterator.next(response);
if (!state.done) {
state.value(foward);
}
}
foward();
};
coroutine(function * () {
var a = yield currier(async, 'a');
var b = yield currier(async, 'b');
var c = yield currier(async, 'c');
console.log(a, b, c);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment