gpt4 book ai didi

使用 Promise 实现 JavaScript Scheduler

转载 作者:行者123 更新时间:2023-11-29 17:43:07 26 4
gpt4 key购买 nike

我正在解决这个有趣的 JavaScript 问题(面试问题),但我陷入了如何使用 Promise 来实现这个问题的困境。

问题:

Write a scheduler in JavaScript that accepts max number of concurrent tasks as a parameter and schedules tasks (each task may take arbitrary time to complete).

请注意,在继续执行其他任务之前,我们一次只需要执行“n”(并发)任务。

这是我的实现:

var exampleTaskA = function () {
setTimeout(function () {
console.log('Task A Done');
}, 1000);
};

function TaskRunner(concurrency) {
this.limit = concurrency;
this.store = [];
this.len = this.store.length;
}

TaskRunner.prototype.push = function (task) {
this.store.push(task);
function getWorker(store, limit) {
if(!store.length) return;

if(store.length <= limit) {
const cur = store.shift();
if(cur) cur();
getWorker(store, limit);
}
}

getWorker(this.store, this.limit);
}

var task = new TaskRunner(2);
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));
console.log(task.push(exampleTaskA));

我如何使用 Promise/async wait 来实现这个?在插入之前我应该​​把一切都围绕在一个 promise 上吗?

有人可以指点一下吗?

最佳答案

因此,如果您可以从任务中返回一个 Promise,则可以与该 Promise 的 then() 绑定(bind),以便在任务完成以及何时可以开始另一个任务时提醒您。

这是一个与您的示例类似的示例,但有一些更改:我们不关心队列的长度 - 您只想知道有多少个事件作业。因此,您可以在开始作业时增加 active ,并在作业完成时减少它。

有很多方法,我肯定会这样做,但以下是一个想法的概述:

const exampleTaskA = (name) => new Promise(resolve => setTimeout(function() {
console.log(`Task ${name} Done`);
resolve()
}, Math.floor(Math.random() * 2000)))

function TaskRunner(concurrency) {
this.limit = concurrency;
this.store = [];
this.active = 0;
}

TaskRunner.prototype.next = function() {
if (this.store.length) this.runTask(...this.store.shift())
}

TaskRunner.prototype.runTask = function(task, name) {
this.active++
console.log(`Scheduling task ${name} current active: ${this.active}`)
task(name).then(() => {
this.active--
console.log(`Task ${name} returned, current active: ${this.active}`)
this.next()
})
}
TaskRunner.prototype.push = function(task, name) {
if (this.active < this.limit) this.runTask(task, name)
else {
console.log(`queuing task ${name}`)
this.store.push([task, name])
}
}

var task = new TaskRunner(2);
task.push(exampleTaskA, 1)
task.push(exampleTaskA, 2)
task.push(exampleTaskA, 3)
task.push(exampleTaskA, 4)
task.push(exampleTaskA, 5)
task.push(exampleTaskA, 6)
task.push(exampleTaskA, 7)

关于使用 Promise 实现 JavaScript Scheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51850236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com