skip to Main Content

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…

2

Answers


  1. Chosen as BEST ANSWER
    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)
    

  2. 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))
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search