Last active
August 29, 2015 14:07
-
-
Save davidchase/bd743b4e0d02f46ceb4e to your computer and use it in GitHub Desktop.
Async with generators
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
// 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