Abdul Raheem Dumrai
Abdul Raheem Dumrai

Reputation: 121

Send multiple requests with Fetch API and wait for their completion before executing another code

I've got too many fetch api requests and some code after that. I want Fetch API to send requests asynchronously but wait for their results before executing next code.

code example:

fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });
fetch(url, {method: 'post', body: someData}).then(response => response.json()).then(data => { if(data.STATUS === 'SUCCESSFUL'){ //some code here } });

//some code to run after above requests processing.

Same multiple fetch requests.

Upvotes: 2

Views: 1089

Answers (1)

user3335966
user3335966

Reputation: 2745

You can use Promise.all()

Promise.all([
  fetch(url, {method: 'post', body: someData}), // first fetch
  fetch(url, {method: 'post', body: someData}), // second fetch
  ...
]).then((data) => {
  const [firstFetchResult, secondFetchResult, ...] = data;
  // data processing
}).then(() => {
  // some code to run after above requests processing.
})

If you have some custom logic for every fetch result - you can use some map for custom functions. In this example mapping is based on map() index (callback's second argument):

// Some functions map - first custom functions for first fetch ect;
const FM_MAP = [
  (data) => data.substring(40, 50).replace('a', 'b'),
  (data) => data.substring(1, 10),
  (data) => [...data.substring(25, 30)].join('-_-')
]

Promise.all([
  fetch('google.com'),
  fetch('google.com'),
  fetch('google.com')
]).then((responses) => Promise.all(
  // you can work with responses just like with regular arrays
  responses
    .map((response, index) => response.text().then((data) => {
      // custom functions for every data result
      console.log(FM_MAP[index](data))
    }))
))

Upvotes: 3

Related Questions