Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
await for all promised to complete and then execute rest of the code

I have this code, I want the code to run for the first 3 push, on execution of the 4th push it should wait for all the promises to complete and then continue the execution. I am not sure if Promise.all is the right way or if there is something wrong with the logic.

var counter = 1;
function TaskRunner(concurrency) {
  this.concurrency = concurrency;
  this.waitList = [];
}

TaskRunner.prototype.push = async function (task) {
  let currentPromise = 'promise'+counter;
  if(counter <= this.concurrency) {
    this[currentPromise] = new Promise((resolve) => {
      resolve(task());
    });
    this[currentPromise].then(() => {
      console.log('completed: ', currentPromise);
    }).catch((e) => {
      console.log('failed: ', currentPromise);
    });
    this.waitList.push(this[currentPromise]);
    counter++;
    return;
  }
  if (counter === this.concurrency + 1) {
    return await Promise.all([this.waitList]).then((values) => {
      console.log('all resolved: ', values);
      task();
      counter++;
    }).catch(() => console.log('error'));
  }
  if (counter > this.concurrency) {
    counter++;
    task();
    return;
  }
  return;
};

function exampleTask() {
  setTimeout(() => console.log('done'), 5000);
}

var r = new TaskRunner(3);

r.push(exampleTask);
r.push(exampleTask);
r.push(exampleTask); 
r.push(exampleTask); // want to wait here for all promise to complete and then continue
r.push(exampleTask);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!