fe-notes
fe-notes copied to clipboard
实现洋葱模型
// 写一个 Task 类
class Task {
constructor() {
// coding here
this.queue = []
this.flag = false
}
add(fn, context, ...args) {
// coding here
let task = {
fn,
context,
args: [...args]
}
this.queue.push(task)
return this
}
run() {
// coding here
let len = this.queue.length
const func = (index = 0) => {
if (this.flag) return Promise.reject(new Error('Follow-up tasks are stopped.'))
if (index === len) return Promise.resolve()
const task = this.queue[index]
return Promise.resolve(task.fn.apply(task.context, [() => func(++index), ...task.args]))
}
return func()
}
stop() {
// coding here
// this.queue = []
this.flag = true
}
}
// 满足
function task1(next) {
setTimeout(() => {
console.log(1)
next()
}, 1000)
}
function task2(next, a) {
// this.stop()
console.log(this.queue)
setTimeout(() => {
console.log(a)
next()
}, 1000)
}
function task3(next, b, c) {
setTimeout(() => {
console.log(b)
console.log(c)
next()
}, 1000)
}
const task = new Task()
task.add(task1).add(task2, task, 2).add(task3, task, 3, 4)
task.run()
// 备注:当任务函数执行 next 的时候,会跳转到下一个任务函数执行