function*foo(a){const sum = a +(yield)return sum
}const it =foo(1)// start
it.next()// pass value instead of yieldconst res = it.next(2)// { value: 3, done: true }
res.value // 3
Getting data from Generator:
function*foo(a){const sum = a +(yield'bar')return sum
}const it =foo(1)// startconst passedValue = it.next()// { value: 'bar', done: false }// pass value instead of yieldconst res = it.next(2)// { value: 3, done: true }
Generators for handling async code:
function*main(){try{const data =yieldfetch('foo.bar')
console.log(data)}catch(err){
console.error(err)}}const it =main()const promise = it.next().value
promise
.then((data)=> it.next(data)).catch((err)=> it.throw(err))