forked from Khaaz/AxonCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.js
More file actions
78 lines (69 loc) · 1.86 KB
/
Queue.js
File metadata and controls
78 lines (69 loc) · 1.86 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
/**
* This default Queue works in a synchronous fashion.
* It will execute all synchronous functions sequentially.
* Any error will be catched and unless specified otherwise won't break the queue execution.
* The queue can be auto executed on add or the execution can be delayed.
*
* @author KhaaZ
*
* @class Queue
*
* @prop {Boolean} [stopOnError=false] Whether to stop the queue execution on error.
*/
class Queue {
/**
* Creates an instance of Queue.
*
* @param {boolean} [stopOnError=false]
*
* @memberof Queue
*/
constructor(stopOnError = false) {
this._functions = [];
this._running = false;
this.stopOnError = stopOnError;
}
/**
* Execute the Queue
*
* @memberof Queue
*/
exec() {
if (this._functions.length > 0) {
this._running = true;
const func = this._functions.shift();
try {
func();
} catch (err) {
if (this.stopOnError) {
throw err;
}
console.log(err);
}
this.exec();
} else {
this._running = false;
}
}
/**
* Adds a function to the queue.
* Automatically wil wrap the function in a closure to keep the function context.
*
* @param {Function} func - The function to run
* @param {Boolean} [toExec=true] - Whether to auto exec the queue on add or not.
* @param {*} args - All arguments the function needs
*
* @memberof Queue
*/
add(func, toExec = true, ...args) {
const fn = this.createClosure(func, ...args);
this._functions.add(fn);
if (toExec && !this._running) {
this.exec();
}
}
createClosure(fn, ...args) {
return () => fn(...args);
}
}
export default Queue;