Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript, detect when a promise in an array of promises is resolved then do something with it

I have the following code :-

      for (let i = 0; i < fdlist.length; i++) {
        let request = fetch(`${domain}/segment?mode=${mode}&type=${type}`,  {    method: 'POST', body: fdlist[i]   }).then((res) => res.json());
        requestlist.push(request)
        console.log(requestlist)
        }
        const allData = Promise.all(requestlist);
        allData.then(async (res) => { 

It sends multiple fetch requests and pushes each one of them to a list, then I do a Promise.all to wait for all of them to resolve and process all the results at once.

My question is, how can I process the promises that resolve right away instead of waiting for all the promises to resolve to begin processing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

just loop through the promises and add "then" clauses:

for (const p of requestlist) {
  p.then(result => ...)
}

// you can always still wait for them all if you want
Promise.all(requestlist).then(...)

you can add your then at the start when you fetch:


for (...) {
  let request = fetch(...)
  const processed = request.then(response => ...)
  requestlist.push(processed)
}

// wait for it all here if you still want
Promise.all(requestlist).then(...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading