任务队列的中断和恢复

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

案例代码

1
/**
2
* 依次顺序执行一系列任务
3
* 所有任务全部完成后可以得到每个任务的执行的结果
4
* 需要返回两个方法,start 用于启动任务, pause 用于暂停任务
5
* 每个任务具有原子性,即不可中断,只能在两个任务之间中断
6
* @param {...Function} tasks 任务列表,每个任务无参、异步
7
*/
8
function processTasks(...tasks) {
9
// 任务队列
10
const tasksQueue = []
11
// 是否正在运行
12
let isRunning = false
13
// 当前执行任务索引
14
let currentIndex = 0
15
16
async function start() {
17
return new Promise((resolve, reject) => {
18
// 如果正在运行则直接返回
19
if (isRunning) return
20
21
isRunning = true
22
// 启动任务
23
while (currentIndex < tasks.length) {
24
// 执行任务
25
tasksQueue.push(tasks[currentIndex++]())
26
if (!isRunning) break
27
}
28
29
// 等待所有任务执行完毕
30
isRunning = false
31
32
resolve(tasksQueue)
33
})
34
}
35
36
function pause() {
37
isRunning = false
38
}
39
40
return {
41
start,
42
pause
43
}
44
}
45
46
const tasks = [
47
async () => {
48
console.log("task1 start");
49
await new Promise((resolve) => setTimeout(resolve, 2000));
50
console.log("task1 end");
51
return "task1 result";
52
},
53
async () => {
54
console.log("task2 start");
55
await new Promise((resolve) => setTimeout(resolve, 1000));
56
console.log("task2 end");
57
return "task2 result";
58
},
59
async () => {
60
console.log("task3 start");
61
await new Promise((resolve) => setTimeout(resolve, 3000));
62
console.log("task3 end");
63
return "task3 result";
64
},
65
];
66
67
const { start, pause } = processTasks(...tasks);
68
69
start().then((results) => {
70
console.log(results);
71
pause();
72
});

输出结果:

1
task1 start
2
task2 start
3
task3 start
4
[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
5
task2 end
6
task1 end
7
task3 end