1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class TaskQueue {
constructor(max = 3) {
// 最大并发数
this.max = max
// 执行中任务队列
this.runList = []
// 执行日志
this.runLog = []
// 待执行任务队列
this.taskList = []
}
// 添加执行任务
addTask(task) {
this.taskList.push(task)
// 每次有任务的添加就出发一次队列的执行,如果当前没有执行的空间会进入排队状态
this.run()
}
// 获取任务列表
getTaskList() {
return this.taskList.map(i => ({ ...i, run: undefined }))
}
// 查看运行中的任务
getRunList() {
return this.runList
}
// 查看缓存中的任务列表
getRunLog() {
return this.runLog
}
// 执行任务
run() {
const length = this.taskList.length
// 获取当前待执行任务条数,若当前没有可执行的任务将跳过后续的执行
if (!length) {
return
}
const min = Math.min(this.max, length)
// 获取当前的执行空间 若没有执行空间则进入等待
for (let i = 0; i < min; i++) {
// 消耗一个执行空间
this.max--
// 取最开始插入的任务 先进先出原则
const task = this.taskList.shift()
// 添加运行在任务信息
this.runList.push(Object.assign({}, task, { run: undefined, callback: undefined }))
// 执行任务
task.run().then(res => {
// 如果传入了回调 执行一次回调
task.callback && task.callback(true)
// 添加信息到 执行日志中
this.runLog.push(Object.assign({ success: true }, task, { run: undefined, callback: undefined }))
console.log(res)
}).catch(err => {
// 如果传入了回调 执行一次回调
task.callback && task.callback(false)
// 添加信息到 执行日志中
this.runLog.push(Object.assign({ success: false }, task, { run: undefined, callback: undefined }))
console.log(err)
}).finally(() => {
// 释放执行空间
this.max++
// 进入下一次执行判断
this.run()
})
}
}
}

const taskQueue = new TaskQueue()

let i = 0

export function createTask(task) {
const index = i++
const defaultInfo = {
index,
name: 'task',
id: Date.now(),
run: task
}
taskQueue.addTask(Object.assign({}, defaultInfo, task))
}

export function getTaskList() {
return taskQueue.getTaskList()
}

export function getRunList() {
return taskQueue.getRunList()
}

export function getRunLog() {
return taskQueue.getRunLog()
}