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 17:49:37 浏览: 81
ruit:功能任务序列化迷你脚本(0.3kb)
Here's one possible implementation of the `run` function:
```javascript
async function run(tasks) {
const taskQueue = Object.entries(tasks)
.filter(([_, task]) => task.dependency.length === 0)
.map(([name, task]) => ({ name, task }))
const runningTasks = {}
while (taskQueue.length > 0) {
const { name, task } = taskQueue.shift()
const dependencies = task.dependency.map((depName) => runningTasks[depName])
const isReady = dependencies.every((dep) => !!dep)
if (!isReady) {
taskQueue.push({ name, task })
continue
}
console.log(`Running task ${name}`)
const taskPromise = task.job()
runningTasks[name] = taskPromise
await taskPromise
delete runningTasks[name]
const dependents = Object.entries(tasks)
.filter(([_, depTask]) => depTask.dependency.includes(name))
.map(([depName, depTask]) => ({ name: depName, task: depTask }))
taskQueue.push(...dependents)
}
}
```
The `run` function uses a task queue to schedule and execute tasks in the correct order. It first adds all tasks with no dependencies to the queue. Then, in each iteration of the loop, it dequeues a task and checks if its dependencies have all finished running. If not, the task is pushed back to the end of the queue. If all dependencies are ready, the task is executed using its `job` function, and its promise is stored in the `runningTasks` object. Once the task finishes, its promise is removed from `runningTasks`, and any dependent tasks are added to the queue.
Note that this implementation assumes that all tasks have either a synchronous `job` function or an asynchronous one that returns a promise. If a task has an asynchronous `job` function that doesn't return a promise, it will need to be wrapped in a `Promise.resolve()` call.
阅读全文