john doe
john doe

Reputation: 9660

Performing Fetch Request in a Loop

I am working on an application that returns a list of ids from first fetch request. After getting the ids, I have to loop through the ids and get details of each item and then display it on the screen.

  fetch(TOP_STORIES)
  .then(function(response){
    return response.json()
  }).then(function(storyIds){
      // storyIds is [22,33,44,55,66,77,88,99,123,213,342,45456,778,888]
      // is this the best way to fetch all the details of the story
      storyIds.forEach(function(storyId){

        let storyDetailsURL = `https://someurl/v0/item/${storyId}.json?print=pretty`

        fetch(storyDetailsURL)
        .then((response) => response.json())
        .then((story) => {
            displayStory(story)
        })
      })

  })

My question is that is looping the best way to get the results?

UPDATE: Promise.all is giving me issues:

enter image description here

UPDATE: Using Async and Await

async function fetchTopHeadlinesAsyncAwait() {

  let response = await fetch(TOP_STORIES)
  let storyIds = await response.json()

  for(let storyId of storyIds) {
    console.log(storyId)
    let storyDetailsURL = `someurl/er/tg/${storyId}.json?print=pretty`
    let response = await fetch(storyDetailsURL)
    let story = await response.json()
    displayStory(story)
  }
}

Upvotes: 2

Views: 7899

Answers (1)

Bjarne Gerhardt-Pedersen
Bjarne Gerhardt-Pedersen

Reputation: 1144

You can use Promise.all functionality to fetch a list of async actions. They will be completed when all are successful.

Here is example of your code with Promise all, let me know how it works :)

const fetchStories = () => {
  let response = await fetch(TOP_STORIES);
  let storyIds = await response.json();

    let urls = [];
    storyIds.forEach(function(storyId) {
      urls.push(`https://someurl/v0/item/${storyId}.json?print=pretty`);
    });

    Promise.all(
      urls.map(url =>
        fetch(url)
          .then(response => response.json())
          .catch(err => console.error(err))
      )
    ).then(stories => stories.forEach(story => displayStory(story)));
}

Upvotes: 4

Related Questions