Skip to content

Instantly share code, notes, and snippets.

@ronapelbaum
Created September 20, 2018 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronapelbaum/4ea32a40b3a32897a9ed1f053da695e0 to your computer and use it in GitHub Desktop.
Save ronapelbaum/4ea32a40b3a32897a9ed1f053da695e0 to your computer and use it in GitHub Desktop.
play with javascript generators
const sleep = ms => new Promise(res => setTimeout(()=>res(ms), ms))
// main1();
// main2();
// run(main3);
run2(main3);
function main1() {
console.log(1);
sleep(100).then(t => console.log(2, t));
sleep(10).then(t => console.log(3, t));
console.log(4);
}
async function main2() {
let t;
console.log(1);
t = await sleep(100);
console.log(2,t);
t = await sleep(10);
console.log(3, t);
console.log(4);
}
function* main3() {
let t;
console.log(1);
t = yield sleep(100);
console.log(2, t);
t = yield sleep(10);
console.log(3, t);
console.log(4);
}
function run(generator) {
const iterator = generator();
function iterate (x){
const it = iterator.next(x);
if (it.done){
return;
}
it.value.then(iterate);
}
iterate()
}
function run2(generator) {
const iterator = generator();
return iterate(iterator.next())
function iterate (it){
if (it.done){
return it.value;
}
const promise = it.value;
return promise.then(x => iterate(iterator.next(x)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment