function getData() {
let num = parseInt(Math.random() * 10);
return new Promise((resolve, reject) => {
setTimeout(() => {
if (num % 3 === 0) reject(num);
else resolve(num);
}, num * 100);
})
}
async function task() {
let result = await getData();
return result;
}
function TaskQueue(taskNum) {
this.count = 0;
this.queue = [];
this.maxTaskNum = taskNum;
this.status = false;
this.init = true;
}
TaskQueue.prototype.push = function(task) {
this.queue.push(task);
if (!this.status && !this.init) this.do();
}
TaskQueue.prototype.do = function() {
this.status = true;
this.init = false;
while (this.queue.length) {
if (this.count < this.maxTaskNum) {
let fn = this.queue.shift();
this.count++;
fn().then((res) => {
console.log(res)
this.count--;
this.do();
}).catch((error) => {
console.log('error response : ', fn.name);
this.count--;
this.do();
});
break;
}
}
this.status = false;
}
let taskQueue = new TaskQueue(3);
for (let i = 0; i < 10; i++) {
taskQueue.push(task);
}
taskQueue.do();