Javascript - Generator in asynchronous

Introduction

Generators can make your asynchronous code look synchronous.

Consider the following example that demonstrates how generators and asynchronous code work well together:

Demo

function getDeveloperDurations() { 
           setTimeout(() => { 
              developerIterator.next({ //from w  ww  . j av a2  s. c  o m
                    Tom: "20m", 
                    Jack: "20m" 
           }); 
        }, 1200); 
} 

function getDeveloperPrices() { 
           setTimeout(function(){ 
              developerIterator.next({ 
                    Tom: "$20", 
                    Jack: "$14" 
                }) 
        }, 1000); 
} 

function *getDevelopers() { 
           const allDevelopers = ["Tom", "Jack"]; 
           const developerDurations = yield getDeveloperDurations(); 
           const developerPrices = yield getDeveloperPrices(); 

           for (let developer of allDevelopers) { 
             console.log(`Bug takes ${developerDurations[developer]} for ${developer} airlines for around ${developerPrices[developer]}`); 
           } 
} 

const developerIterator = getDevelopers(); 

developerIterator.next();

Result

Here, genDevelopers() is a generator function that returns an iterator.

On calling the next() method of the returned iterator, the generator execution gets to the first yield statement where getDeveloperDurations() is invoked.

getDeveloperDurations() is an asynchronous function that uses setTimeout to delay the execution by 1.2s and calls next() method on the iterator guaranteeing that developerDurations will be correctly assigned.

Having a yield statement prevents the value from being assigned until the setTimeout function has executed.

Generators help us write blocking code when using asynchronous operations, making the code look more synchronous.

Related Topic