链式调用和延迟执行

作者:xie392地址:https://v.douyin.com/ieaCTbNF/更新时间:2024-12-21

案例代码

1
function arrange(name) {
2
// 任务队列
3
const tasks = []
4
5
// 添加任务
6
tasks.push(() => {
7
console.log(`${name} is notified`)
8
})
9
10
function doSomething(action) {
11
tasks.push(() => {
12
console.log(`Start to ${action}`)
13
})
14
return this
15
}
16
17
function wait(sec) {
18
tasks.push(() => new Promise(resolve => {
19
setTimeout(resolve, sec * 1000)
20
}))
21
return this
22
}
23
24
function waitFirst(sec) {
25
// 在任务队列的最前面插入一个任务
26
tasks.unshift(() => new Promise(resolve => {
27
setTimeout(resolve, sec * 1000)
28
}))
29
return this
30
}
31
32
async function execute() {
33
for (const t of tasks) {
34
await t()
35
}
36
}
37
38
return {
39
do: doSomething,
40
wait: wait,
41
waitFirst: waitFirst,
42
execute: execute
43
}
44
}
45
46
47
arrange('William').execute()
48
// > William is notified
49
50
51
arrange('William').do('commit').execute()
52
// > William is notified
53
// > Start to commit
54
55
56
arrange('William').wait(5).do('commit').execute()
57
// > William is notified
58
// 等待5秒
59
// > Start to commit
60
61
arrange('William').waitFirst(5).do('commit').execute()
62
// 等待5秒
63
// > William is notified
64
// > Start to commit

输出结果:

1
William is notified
2
William is notified
3
William is notified
4
Start to commit
5
William is notified
6
Start to commit
7
Start to commit