1
|
# run-queue
|
2
|
|
3
|
A promise based, dynamic priority queue runner, with concurrency limiting.
|
4
|
|
5
|
```js
|
6
|
const RunQueue = require('run-queue')
|
7
|
|
8
|
const queue = new RunQueue({
|
9
|
maxConcurrency: 1
|
10
|
})
|
11
|
|
12
|
queue.add(1, example, [-1])
|
13
|
for (let ii = 0; ii < 5; ++ii) {
|
14
|
queue.add(0, example, [ii])
|
15
|
}
|
16
|
const finished = []
|
17
|
queue.run().then(
|
18
|
console.log(finished)
|
19
|
})
|
20
|
|
21
|
function example (num, next) {
|
22
|
setTimeout(() => {
|
23
|
finished.push(num)
|
24
|
next()
|
25
|
}, 5 - Math.abs(num))
|
26
|
}
|
27
|
```
|
28
|
|
29
|
would output
|
30
|
|
31
|
```
|
32
|
[ 0, 1, 2, 3, 4, -1 ]
|
33
|
```
|
34
|
|
35
|
If you bump concurrency to `2`, then you get:
|
36
|
|
37
|
```
|
38
|
[ 1, 0, 3, 2, 4, -1 ]
|
39
|
```
|
40
|
|
41
|
The concurrency means that they don't finish in order, because some take
|
42
|
longer than others. Each priority level must finish entirely before the
|
43
|
next priority level is run. See
|
44
|
[PRIORITIES](https://github.com/iarna/run-queue#priorities) below. This is
|
45
|
even true if concurrency is set high enough that all of the regular queue
|
46
|
can execute at once, for instance, with `maxConcurrency: 10`:
|
47
|
|
48
|
```
|
49
|
[ 4, 3, 2, 1, 0, -1 ]
|
50
|
```
|
51
|
|
52
|
## API
|
53
|
|
54
|
### const queue = new RunQueue(options)
|
55
|
|
56
|
Create a new queue. Options may contain:
|
57
|
|
58
|
* maxConcurrency - (Default: `1`) The maximum number of jobs to execute at once.
|
59
|
* Promise - (Default: global.Promise) The promise implementation to use.
|
60
|
|
61
|
### queue.add (prio, fn, args)
|
62
|
|
63
|
Add a new job to the end of the queue at priority `prio` that will run `fn`
|
64
|
with `args`. If `fn` is async then it should return a Promise.
|
65
|
|
66
|
### queue.run ()
|
67
|
|
68
|
Start running the job queue. Returns a Promise that resolves when either
|
69
|
all the jobs are complete or a job ends in error (throws or returns a
|
70
|
rejected promise). If a job ended in error then this Promise will be rejected
|
71
|
with that error and no further queue running will be done.
|
72
|
|
73
|
## PRIORITIES
|
74
|
|
75
|
Priorities are any integer value >= 0.
|
76
|
|
77
|
Lowest is executed first.
|
78
|
|
79
|
Priorities essentially represent distinct job queues. All jobs in a queue
|
80
|
must complete before the next highest priority job queue is executed.
|
81
|
|
82
|
This means that if you have two queues, `0` and `1` then ALL jobs in `0`
|
83
|
must complete before ANY execute in `1`. If you add new `0` level jobs
|
84
|
while `1` level jobs are running then it will switch back processing the `0`
|
85
|
queue and won't execute any more `1` jobs till all of the new `0` jobs
|
86
|
complete.
|