Javascript - Generators with finally


You can avoid the immediate sequence termination by wrapping up the code inside try-finally block.

In this way it ensures that the code with the finally clause will execute in case of completion, whether early or when the yield statements are exhausted.

This can be helpful in performing any cleanup or closing operations after the sequence has ended.

function *getFruits() { 
          try { 
            yield "XML"; 
            yield "Keyboard"; 
            yield "Screen"; 

          finally { 
            console.log("inside finally"); 
            yield "watermelon"; 
const fruitIterator = getFruits(); 
console.log(; // { value: 'XML', done: false } 
// inside finally 
// { value: 'watermelon', done: false } 
// { value: 'kiwi', done: true } 
// { value: undefined, done: true } 

Related Topic