DEV Community

Cover image for Unlocking Lazy Evaluation: Mastering JavaScript Generators
Ananth Iyer
Ananth Iyer

Posted on

Unlocking Lazy Evaluation: Mastering JavaScript Generators

This is my first post on Dev.to and excited to showcase JavaScript Generators with Fetch API.

I have been coding JavaScript for long time and never heard of Generators in JS. What is it? Why to use? Where to use it?

Recently, I show a YouTube video on it but still was confused to use it.

I got deep dive into the Generators and it is used for lazy evaluation iterators in loops. Again I got confused because I never used huge array to iterator. Why to use it? πŸ€”

I looked for real world use case of Generators and found it can be used with Fetch API for pagination or search etc.

So let's code it

// Generator function to fetch paginated data
function* fetchPaginatedData(apiUrl) {
    let page = 1;
    let hasMoreData = true;
    let limit = 10;

    while (hasMoreData) {
        const response = yield fetch(`${apiUrl}${page}`)
            .then(res => res.json())
            .catch(err => console.error('Fetch error:', err));

        if (response && response.id && page < limit) {
            page++;
        } else {
            hasMoreData = false;
        }
    }
}

// Function to handle the generator
async function handleDataFetching(apiUrl) {
    const dataIterator = fetchPaginatedData(apiUrl);
    let result = dataIterator.next();

    while (!result.done) {
        const data = await result.value;
        console.log('Fetched data:', data);
        result = dataIterator.next(data);
    }
}

// Usage
const apiUrl = 'https://jsonplaceholder.typicode.com/posts/';
handleDataFetching(apiUrl);
Enter fullscreen mode Exit fullscreen mode

In the above code:

  • Generator Function: fetchPaginatedData is a generator that yields a fetch request for each page of data.
  • Dynamic Iteration: The while loop continues until it reached the limit of 10 page.
  • Handling the Generator: handleDataFetching function manages the generator, making asynchronous fetch calls and processing the data.

Browser support for Generators: All major supports Chrome(v39), Firefox(v26), Safari (v10), Edge (v12), Opera (v26) and all mobile browsers too. It means you can start using Generators without fear of compatibility issues and show your friends the smart coding.

Benefits of Using Generators

  • Lazy Evaluation: Generators produce values on demand, which means they only compute values when needed.
  • Improved Performance: By processing data in chunks, generators can help avoid blocking the main thread, leading to smoother performance and better user experience.
  • Simplified Code: Generators can make asynchronous code easier to read and maintain by avoiding deeply nested callbacks or complex promise chains.
  • Memory usage: It helps lower memory usage in the browser because of lazy evaluation, meaning values are generated on-the-fly rather than all at once. It can control for/while loops, fetch API execution on demand.

You can run the code here: https://runjs.co/s/ljJq79Wev

API Data by {JSON} Placeholder: https://jsonplaceholder.typicode.com/

Hope you find it helpful and added value to your knowledge.

Regards.

Top comments (0)