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);