以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - JavaScript 代码题
179. Implement AsyncTaskQueue
请参考以下解答:
class AsyncTaskQueue { constructor(concurrency) { this.concurrency = concurrency; this.runningCount = 0; this.queue = []; this.executeNext = this.executeNext.bind(this); } async executeNext() { if (this.runningCount < this.concurrency && this.queue.length > 0) { this.runningCount++; const task = this.queue.shift(); try { await task(); } catch (error) { // Ignore Promise rejection } this.runningCount--; this.executeNext(); } } queue(task) { this.queue.push(task); this.executeNext(); }}
在这段代码中,我们首先定义了AsyncTaskQueue类,构造函数中传入并初始化了并发限制concurrency、运行中任务数runningCount、任务队列queue,同时绑定executeNext方法。executeNext方法用于执行下一个异步任务,当运行中任务数小于并发限制并且队列中有任务时,出队列一个任务执行,若任务有异常则捕获忽略。queue方法用于将一个异步任务加入队列,并启动执行。
在示例用法中,我们先创建了一个最大并发数为2的AsyncTaskQueue实例,然后创建了三个异步任务task1、task2和task3。分别将这三个任务加入队列中,根据队列的FIFO特性和并发限制,第一个和第二个任务会立即开始执行,第三个任务会等待直到前两个任务中有一个执行完毕。