Vitaminaq / interview-collection

前端面试合集
3 stars 0 forks source link

实现一个异步任务执行器 AsyncWorker,此 AsyncWorker: 最多只能同时执行 capacity,个异步任务. 若正在执行的任务数达到 capacity,则新加入的任务需要等待其中一个正在执行的任务完成后才能被执行。 #12

Open Vitaminaq opened 2 years ago

Vitaminaq commented 2 years ago
class AsyncWorker {
    queue = [];
    count = 0;
    constructor(capacity) {
        this.capacity = capacity;
    }
    shiftQueue() {
        console.log('当前执行数:', this.count);
        this.count--;
        console.log('当前队列长度:', this.queue.length);
        const t = this.queue.shift();
        t && this.exec(t);
    }
    async exec(task) {
        if (this.count < this.capacity) {
            this.count++;
            try {
                const r = await task();
                this.shiftQueue();
                return r;
            } catch (e) {
                this.shiftQueue();
                return e;
            }
        } else {
            this.queue.push(task)
        }
    }
}
function cp(time, s) {
    return () =>  new Promise((resolve, reject) => {
        setTimeout(() => {
            s ? resolve() : reject();
        }, time)
    })
}
const a = new AsyncWorker(2);
for (let i = 1; i < 10; i++) {
    a.exec(cp(i * 1000, i % 2))
}