const sleep = (delay) => new Promise((r) => setTimeout(r, delay)) const tasks = { a: { job: async function () { await sleep(1000) console.log('Tasks A running') }, dependency: ['c', 'b'], }, b: { job: async function () { await sleep(3000) console.log('Tasks B running') }, dependency: [], }, c: { job: function () { console.log('Tasks C running') }, dependency: [], }, d: { job: function () { console.log('Tasks D running') }, dependency: ['c'], }, } function run(tasks) { // ...Write your answer here // The params `tasks` can be multiple of task, not just a、b、c、d. so don't answer with `a.job()` etc. // Answer should not include keyword of a/b/c/d } run(tasks) // desired outcome: // task B and task C get fired immediately // -> task D gets fired after task C finishes while task B is running in the background asyncrhously // -> once task B finishes, task A gets to run
时间: 2023-11-28 22:47:33 浏览: 60
以下是实现该任务的代码:
```
async function run(tasks) {
// Create a map to store the tasks
const taskMap = new Map()
// Add each task to the map and set its status to 'pending'
for (const [taskName, task] of Object.entries(tasks)) {
taskMap.set(taskName, { ...task, status: 'pending' })
}
// Loop through the map and execute tasks in the correct order
for (const [taskName, task] of taskMap) {
// Check if the task has any dependencies
if (task.dependency.length === 0) {
// If it doesn't have any dependencies, execute the task
await task.job()
task.status = 'done'
} else {
// If it has dependencies, wait for them to finish before executing the task
const dependencies = task.dependency.filter((dep) => taskMap.get(dep).status !== 'done')
if (dependencies.length === 0) {
// If all dependencies are done, execute the task
await task.job()
task.status = 'done'
} else {
// If not all dependencies are done, wait for them to finish
await Promise.all(dependencies.map((dep) => taskMap.get(dep).promise))
await task.job()
task.status = 'done'
}
}
// Set the promise for the task so that its dependencies can wait for it to finish
task.promise = Promise.resolve()
}
}
run(tasks)
```
这个函数会创建一个任务 Map 并将每个任务添加到其中。然后,它会遍历任务 Map 并按正确的顺序执行任务。如果任务有依赖项,则它会等待所有依赖项完成后再执行任务。如果任务没有依赖项,则它会立即执行。
在这个特定的例子中,任务 B 和任务 C 没有依赖项,因此它们会立即执行。任务 D 依赖于任务 C,因此它会等待任务 C 完成后再执行。任务 A 依赖于任务 B 和任务 C,但是由于任务 B 是异步的,因此任务 A 可以在后台运行,等待任务 C 完成后再执行。
阅读全文