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

Time:06-14

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?

CodePudding user response:

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(...)
  • Related