DEV Community

LuBustos
LuBustos

Posted on

How to make a request within a loop

Hey! This is my first blog here, so I hope you enjoy it :p

Let's go

There are two ways to make a request within a loop: we have the sequence way or the parallel way.

I made a small example in codesandbox to show a practical case.

Here is the link: Example

  • Sequence method:
const sequence = async () => {
  try {
    for (const color of colors) {
      const response = await save(color);
      console.log("response sequence", response);
    }
  } catch (error) {
    console.error(error);
  }
};
Enter fullscreen mode Exit fullscreen mode

In this way we have to use a for...of to loop every item of the array and to execute the method save within the loop.
In this case the code will be executed line by line, which means first the method save and then the console.log.

And this is the result:

saved it {id: 1, color: "red"}
response sequence {id: 1, color: "red"}
saved it {id: 2, color: "green"}
response sequence {id: 2, color: "green"}
Enter fullscreen mode Exit fullscreen mode

This way is a little bit slow, but if you are waiting for a response from the server, such as an id, it is useful.

  • Parallel method
const parallel = async () => {
  try {
    await Promise.all(
      colors.map(async (color) => {
        const response = await save(color);
        console.log("response parallel", response);
      })
    );
  } catch (error) {
    console.error(error);
  }
};
Enter fullscreen mode Exit fullscreen mode

In this case we are using a Promise.all within a .map. This is important because this method returns an array of promises and the Promise.all will execute all the promises together.

Looping the array, every element in it will enter the save method and, after this, the next line will be executed, in this case the console.log.

This is the result:

saved it {id: 1, color: "red"}
saved it {id: 2, color: "green"}
response parallel {id: 1, color: "red"}
response parallel {id: 2, color: "green"}
Enter fullscreen mode Exit fullscreen mode

You can appreciate better from the link that I attached or maybe creating a file.js and debugging step by step.

This is all for today.
I hope you can find this useful and I will be expecting your comments.

Top comments (2)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
lubustos profile image
LuBustos

Thanks.
I appreaciate it.