Advertisement
Advanced JavaScript, Iterators & Generators

How do you use generator.throw() and generator.return() to control a running generator externally?

Short answer

generator.throw(err) resumes the generator by throwing err at the current yield point, letting the generator's own try/catch handle it. generator.return(value) forces the generator to terminate immediately as if a return statement executed there, running any finally blocks first.

Save JavaScript mock interview
Advertisement
AModel answer
generator.throw(err) resumes the generator by throwing err at the current yield point, letting the generator's own try/catch handle it. generator.return(value) forces the generator to terminate immediately as if a return statement executed there, running any finally blocks first.
function* gen() {
  try {
    yield 1;
  } catch (err) {
    console.log('caught:', err.message);
    yield 2;
  }
}
const it = gen();
it.next();          // { value: 1, done: false }
it.throw(new Error('oops')); // logs 'caught: oops', returns { value: 2, done: false }
Real-world example
Cancelling an in-progress generator-based task pipeline cleanly from outside code.
Likely follow-ups
  • What's the difference between calling return() and simply breaking out of a for...of loop over the generator?
Related topics