Javascript - Generators with finally

Introduction

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(fruitIterator.next()); // { value: 'XML', done: false } 
console.log(fruitIterator.return("kiwi")); 
// inside finally 
// { value: 'watermelon', done: false } 
console.log(fruitIterator.next()); 
// { value: 'kiwi', done: true } 
console.log(fruitIterator.next()); 
// { value: undefined, done: true } 

Related Topic