Last active
November 27, 2017 16:06
-
-
Save creationix/5761021 to your computer and use it in GitHub Desktop.
A tiny generator helper for consuming callback code directly
This file contains 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
function run(generator) { | |
var iterator = generator(resume); | |
var data = null, yielded = false; | |
iterator.next(); | |
yielded = true; | |
check(); | |
function check() { | |
while (data && yielded) { | |
var err = data[0], item = data[1]; | |
data = null; | |
yielded = false; | |
if (err) return iterator.throw(err); | |
iterator.send(item); | |
yielded = true; | |
} | |
} | |
function resume() { | |
data = arguments; | |
check(); | |
} | |
} |
I know this is super old but to anyone looking into generators now, iterator.send(item)
should now be iterator.next(item)
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another example showing it can withstand sync callbacks without blowing the stack