How to Fetch Data in a JavaScript For Loop?

Estimated read time 1 min read

You can fetch data in a JavaScript for loop by making an asynchronous request inside the loop and waiting for the response before continuing to the next iteration. Here’s an example using the fetch API:

const urls = [
  "https://jsonplaceholder.typicode.com/posts/1",
  "https://jsonplaceholder.typicode.com/posts/2",
  "https://jsonplaceholder.typicode.com/posts/3"
];

async function fetchData(url) {
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
}

for (const url of urls) {
  fetchData(url);
}

In this example, the fetchData function is defined to make an asynchronous request for a given URL using the fetch API. The function returns a promise that resolves to the JSON data from the response. The for loop then iterates over an array of URLs and calls fetchData for each URL, waiting for each response to come back before proceeding to the next iteration.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply