skip to Main Content

For example if I have some list of IDs in ItemList component:

{itemIds.map((itemId, index) => { return <Item key={itemId} itemId={itemId} />; })}

and then inside Item component I make API request for each of the items by their ID.

How do I make these ID requests to run in parallel in the best possible way? Do I really have to use Promise.all() or Promise.allSettled()? Any alternatives to that?

2

Answers


  1. It depends, if you need all you data to resolved together you need to use Promise.all or Promise.allSettled, if you want to show whatever item resolved you can send the request from each item.

    But from the backend perspective, whatever method you use to call the data this way will lead to a lot of requests to the server, especially if there are a lot of items.

    It would be better to make an API to send the IDS and return all these items together in one request and from the front end, you loop through the items.

    Login or Signup to reply.
  2. An alternative would be to use async/await in a for loop, like this example :

    async function getItems(itemIds) {
      const items = [];
      for (const itemId of itemIds) {
        const response = await fetch(`https://example.com/items/${itemId}`);
        const data = await response.json();
        items.push(data);
      }
      return items;
    }
    
    getItems(itemIds)
      .then(items => {
        // Handle the array of item data
      })
      .catch(error => {
        // Handle any errors
      });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search