Created
July 18, 2016 12:00
-
-
Save vitalymak/b6c981387b23a6649ffba685143e54d7 to your computer and use it in GitHub Desktop.
ES6 generators: yield yield* for of difference
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
'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