0

In Typescript, how can I make multiple http request in parallel and process each of the response independently?

I read posts like: https://melvingeorge.me/blog/do-multiple-fetch-requests-parallel-javascript?msclkid=27e3e64fbb6611ec99bd559527fe2a91 Resolving multiple fetch request in parallel

Both suggest using 'Promise.all' which seems to me the processing will happen only when reponsees from ALL requests come back.

My question is how can I make the request in paraell and process each of the response as they come back? Or this is not possible since JavaScript is a single threaded?

Thank you.

n179911a
  • 125
  • 1
  • 8

1 Answers1

1

You're right about Promise.all, that is intended for waiting until all of a set of Promises have all resolved. It creates a new Promise that resolves only once all the Promises used to create it have resolved, then passes an array of the values they resolved with to the "all" Promise. You can still make requests in parallel, but this function is for when you want to wait for them all to resolve before handling the result.

If you just need to handle each Promise as it resolves, then you can just bind a callback to them and send off all your requests. As each Promise resolves, its handler will be executed. No special extra code is required.

A simple approach like this will let you make multiple requests and handle each one as its Promise resolves.

fetch(url1).then(handleRequest1).catch(handleError1);
fetch(url2).then(handleRequest2).catch(handleError2);
fetch(url3).then(handleRequest3).catch(handleError3);
Mark Hanna
  • 3,206
  • 1
  • 17
  • 25