Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created January 29, 2023 02:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmbaughman/96721ee088d08d27514cfc3c49d1d13b to your computer and use it in GitHub Desktop.
Save cmbaughman/96721ee088d08d27514cfc3c49d1d13b to your computer and use it in GitHub Desktop.
The JavaScript feature, Generators

Here is an example of using JavaScript generators to handle multiple HTTP requests in a sequential manner:

const fetch = require("node-fetch");

function* fetchUsers() {
  const user1 = yield fetch("https://jsonplaceholder.typicode.com/users/1");
  const user2 = yield fetch("https://jsonplaceholder.typicode.com/users/2");
  const user3 = yield fetch("https://jsonplaceholder.typicode.com/users/3");
  const user4 = yield fetch("https://jsonplaceholder.typicode.com/users/4");
}

const generator = fetchUsers();
const user1 = generator.next().value;
const user2 = generator.next().value;
const user3 = generator.next().value;
const user4 = generator.next().value;

Promise.all([user1, user2, user3, user4])
  .then((responses) => {
    return Promise.all(responses.map((res) => res.json()));
  })
  .then((users) => {
    console.log(users);
  });

This code uses the fetch' function to make four HTTP requests to an API that returns user data, it then uses a generator function to handle the requests in a sequential manner, and the yield keyword is used to pause the execution of the generator function until the current request is completed. The generator function returns an iterator, which is assigned to the `generator' variable.

Here's a browser based version:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function* fetchUsers() {
        const user1 = yield fetch("https://jsonplaceholder.typicode.com/users/1");
        const user2 = yield fetch("https://jsonplaceholder.typicode.com/users/2");
        const user3 = yield fetch("https://jsonplaceholder.typicode.com/users/3");
        const user4 = yield fetch("https://jsonplaceholder.typicode.com/users/4");
      }

      const generator = fetchUsers();
      generator.next().value
        .then((res) => {
          return res.json();
        })
        .then((user) => {
          document.getElementById("user1").innerHTML = JSON.stringify(user);
          return generator.next().value;
        })
        .then((res) => {
          return res.json();
        })
        .then((user) => {
          document.getElementById("user2").innerHTML = JSON.stringify(user);
          return generator.next().value;
        })
        .then((res) => {
          return res.json();
        })
        .then((user) => {
          document.getElementById("user3").innerHTML = JSON.stringify(user);
          return generator.next().value;
        })
        .then((res) => {
          return res.json();
        })
        .then((user) => {
          document.getElementById("user4").innerHTML = JSON.stringify(user);
        });
    </script>
  </head>
  <body>
    <div id="user1"></div>
    <div id="user2"></div>
    <div id="user3"></div>
    <div id="user4"></div>
  </body>
</html>

The fetch function is used to make four HTTP requests to an API that returns user data, it then uses a generator function to handle the requests in a sequential manner, and the yield keyword is used to pause the execution of the generator function until the current request is completed. The generator function returns an iterator, which is assigned to the generator variable.

The next() method is called on the iterator to move to the next yield statement in the generator function. This causes the corresponding fetch call to be made, and the promise returned by the fetch call is assigned to the variable on the left of the yield statement.

The promises are passed to .then and the response is parsed to json and the user data is displayed in the corresponding div element in the HTML document. This allows for a more readable and maintainable way of handling multiple asynchronous requests, as you can see the requests are happening one after the other, in a sequential manner, and the data is displayed in a visual way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment