-1

In JavaScript, in the array of promises (can have n promises), run first n promises, when finished, run another n;

Example:

const promises = [Promise_1, Promise_2, Promise_3, Promise_4, Promise_5, Promise_6];

Run Promise_1 and Promise_2, when both finish, run Promise_3, Promise_4, then Promise_5, Promise_6.

axios.post('/api') axios.post('/api') WAIT
axios.post('/api') axios.post('/api') WAIT axios.post('/api') axios.post('/api')

Tried with Promise.all, for of loop, async/await...

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Vojin Purić Jul 16 '23 at 19:39

2 Answers2

0

const array = [wait, wait, wait, wait, wait, wait]

run(array)

async function run(array, batch = 2) {
  let i = 0
  while (i < array.length) {
    await Promise.all(array.slice(i, i + batch).map(fn => fn()))
    console.log(`finished [${i} - ${i + batch}]`)
    i += batch
  }
}

function wait() {
  return new Promise(r => setTimeout(r, 1000))
}
Konrad
  • 21,590
  • 4
  • 28
  • 64
-1
const promises = [];
const apiPromises = [promise_1, promise_2, promise_3, ....etc]; 
let counter = 1;

const resolvePromisesSeq = async () => {
  for (const prom of apiPromises) {
    if (counter % 3 !== 0) {
      promises.push(axios.post('/fakeApi/' + prom));
    } else {
      await axios.post('/fakeApi/' + prom);
    }
    counter++;
  }
  return Promise.all(promises);
};
resolvePromisesSeq().then(whatEverYouWant)
  • This code doesn't wait for each batch of three promises to resolve, it waits for every third promise to resolve. If 4 or 5 takes longer to resolve than 6 then 7, 8 and 9 will be running at the same time as 4 or 5. – Quentin Jul 18 '23 at 14:44
  • The value returned **discards** every third promise so `whatEverYouWant` won't get all the data. – Quentin Jul 18 '23 at 14:44
  • To help people understand your answer better, please provide some extra information along with the code you shared. – Sally loves Lightning Jul 22 '23 at 19:09