Last active
November 16, 2020 07:07
-
-
Save Hahet/b0aff01e48c3253356da7d296fbb8d0d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 实现带异步任务的链式调用:chain.eat().sleep(5).work().eat().work().sleep(10) | |
// 链式调用:函数都 return this | |
// 链式调用时(同步过程),会将每个任务(函数)放到 队列中(tasks) | |
// 使用 start 函数异步开始执行第一个任务( next 函数第一次调用) 每一个任务执行完就 再调用 next 函数,next 会取出下一个任务出来执行 | |
class Chaos { | |
constructor() { | |
this.tasks = [] | |
const fn = () => { | |
console.log('chain start') | |
this.next() | |
} | |
this.tasks.push(fn) | |
} | |
start() { | |
// 启动调用 | |
Promise.resolve().then(() => { | |
this.next() | |
}) | |
return this | |
} | |
next() { | |
const fn = this.tasks.shift(); | |
fn && fn() | |
} | |
sleep(n) { | |
const fn = () => { | |
console.log('sleep start') | |
setTimeout(() => { | |
console.log('sleep end') | |
this.next() | |
}, n * 1000) | |
} | |
this.tasks.push(fn) | |
return this | |
} | |
work() { | |
const fn = () => { | |
console.log('work') | |
this.next() | |
} | |
this.tasks.push(fn) | |
return this | |
} | |
eat() { | |
const fn = () => { | |
console.log('eat') | |
this.next() | |
} | |
this.tasks.push(fn) | |
return this | |
} | |
} | |
const chain = () => { | |
return new Chaos().start() | |
} | |
chain().eat().sleep(5).work().eat().work().sleep(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
更简单的使用 promise 实现