Techscrypt

Generator Functions in Javascript

javascriptgenerators

Generator functions can be used to define an iterative algorithm within a single function whose execution is not continuous. Generator functions run a special type of iterator called a generator. These functions are written using the function* syntax.

Implementation

A generator function executes until it encounters a yield keyword. The values of the function can be consumed using the next method or iterating over it using a for loop.

function* counter(end=100) {
let count = 0;
for (let i = 0; i < end; i++) {
count++;
yield i;
}
return count;
}

// Usage

const counts = counter(5);
for (const c of counts) {
console.log(c);
}

// Result: Numbers 0-4 are logged with each iteration of the for loop

Processing multiple promises sequentially

Here is an example where multiple promises are processed sequentially (situations where data needs to be fetched from apis in a particular order). The await… for… of loop can be used to iterate through the generated values.

// This method simulates calling an api that takes 1s to resolve
async function getValue(a) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(a);
}, 1000);
});
}

async function* generateDelayedValues(end) {
for (let i = 1; i <= end; i++) {
yield getValue(i);
}
}


async function run() {
const values = generateDelayedValues(5);
for await (const value of values) {
console.log(value)
}
}

run();

// Result: The numbers 1 to 5 are logged at an interval of 1s

References

  1. MDN Iterators and Generators
  2. MDN for await...of Loop