Parallel Fetch Requests using Promise.all()

When we need to do multiple fetch requests we can use Promise.all() to make our fetch promises parallels, which can improve the app performance.

An example of this as follows:

const dataFetch = ['data1', 'data2']
const promiseArray = []

dataFetch.forEach(datum => {
  const fetchPromise = fetch(`https://somewhereremote.com/${datum}`, {method: 'GET'})
  promiseArray.push(fetchPromise)
})

Promise.all(promiseArray)
.then(values => { 
  console.log(values);
})
.catch(error => { 
  console.error(error.message)
});

Reference:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.