-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_queue_run.cjs
More file actions
105 lines (93 loc) · 2.19 KB
/
simple_queue_run.cjs
File metadata and controls
105 lines (93 loc) · 2.19 KB
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
95
96
97
98
99
100
101
102
103
104
105
/**
* CommonJS build of simpleQueueRun (converted from ESM source).
*/
const defaultOption = {
concurrence: 5,
interval: 0,
};
function simpleQueueRun(tasks, option) {
return new Promise((resolve, reject) => {
if (
!(
Array.isArray(tasks) &&
tasks.every((item) => typeof item === "function")
)
) {
return reject(new Error("tasks must be function array"));
}
if (tasks.length === 0) {
return resolve();
}
const optionInner = Object.assign({}, defaultOption, option);
let lastTaskIndex = 0;
const execWindows = [];
execWindows.length = optionInner.concurrence || 5;
execWindows.fill(null);
function pushTasks() {
const min = Math.min(tasks.length, execWindows.length);
for (let i = 0; i < min; i++) {
execWindows[i] = tasks[i];
tasks[i] = null;
}
lastTaskIndex = min - 1;
}
function runTasks() {
execWindows.forEach((task, index) => {
if (typeof task === "function") {
runTask(task, index);
}
});
}
function runTask(task, index) {
try {
const result = task();
if (result instanceof Promise) {
result
.then(() => {
if (optionInner.interval > 0) {
setTimeout(
() => releaseAndCallNext(index),
optionInner.interval,
);
} else {
releaseAndCallNext(index);
}
})
.catch(reject);
} else {
setTimeout(() => releaseAndCallNext(index), optionInner.interval);
}
} catch (err) {
reject(err);
}
}
function releaseAndCallNext(index) {
if (optionInner.signal && optionInner.signal.aborted) {
return;
}
execWindows[index] = null;
const nextIndex = lastTaskIndex + 1;
const nextTask = tasks[nextIndex];
if (nextTask) {
tasks[nextIndex] = null;
lastTaskIndex = nextIndex;
execWindows[index] = nextTask;
runTask(nextTask, index);
}
const allFree = execWindows.every((item) => item === null);
if (!nextTask && allFree) {
tasks.length = 0;
resolve();
}
}
function onAbort() {
reject(new Error("aborted"));
}
if (optionInner.signal) {
optionInner.signal.addEventListener("abort", onAbort);
}
pushTasks();
runTasks();
});
}
module.exports = simpleQueueRun;