Skip to content

Instantly share code, notes, and snippets.

@vitalymak
Created July 18, 2016 12:00
Show Gist options
  • Save vitalymak/b6c981387b23a6649ffba685143e54d7 to your computer and use it in GitHub Desktop.
Save vitalymak/b6c981387b23a6649ffba685143e54d7 to your computer and use it in GitHub Desktop.
ES6 generators: yield yield* for of difference
'use strict';
function* f1 () {
yield 'f1 yield #1';
yield 'f1 yield #2';
return 'f1 RETURN';
}
function* f2 () {
yield 'f2 yield #1';
// we have in res1 f1 return value
let res1 = yield *f1();
console.log(`res1: ${res1}`);
console.log('');
// f1 return value is skipped silently
let gen = f1();
let val;
let res;
for (val of gen) {
res = yield val;
}
console.log(`val: ${val}`);
console.log(`res: ${res}`);
console.log('gen.next():', gen.next());
console.log('');
// compare the results while manual iterate
let gen2 = f1();
yield gen2.next().value;
yield gen2.next().value;
yield gen2.next().value;
yield gen2.next().value;
}
let gen = f2();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
/*
{ value: 'f2 yield #1', done: false }
{ value: 'f1 yield #1', done: false }
{ value: 'f1 yield #2', done: false }
res1: f1 RETURN
{ value: 'f1 yield #1', done: false }
{ value: 'f1 yield #2', done: false }
val: f1 yield #2
res: undefined
gen.next(): { value: undefined, done: true }
{ value: 'f1 yield #1', done: false }
{ value: 'f1 yield #2', done: false }
{ value: 'f1 RETURN', done: false }
{ value: undefined, done: false }
{ value: undefined, done: true }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment