-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromiseQueue.js
66 lines (56 loc) · 1.51 KB
/
promiseQueue.js
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
/**
* A module for running an array of promise returning functions.
* @module simple-queue
*/
var Promise = require( "promise" )
/**
* Function to process queues. Returns a promise for queue completion.
* @param {array} queue - An array of functions which return promises
* @param {object} options - Options for the queue
*/
function queue( queue, options ){
return Promise( function( resolve, reject ){
// Determine concurrency limit
if( !options ){
options = {}
}
var limit = queue.length
if( options.concurrency ){
if( options.concurrency < queue.length ){
limit = options.concurrency
}
}
// Track existence of queue promise rejections
haveRejections = false
/**
* Run the next task, until the queue is done
*/
var jobCount = queue.length
var jobsDone = 0
function next(){
if( jobCount > jobsDone && !( haveRejections && options.abortOnReject ) ){
// Queue has stuff, and its not time to reject
var task = queue.pop()()
task.then( function fulfilled(){
jobsDone += 1
next()
}, function rejected(){
haveRejections = true
jobsDone += 1
next()
} )
} else if( haveRejections && options.abortOnReject ){
// Bail out early
reject()
} else {
// All work done
resolve()
}
}
// Start concurrent jobs
for( var i = 0; i < limit; i += 1 ){
next()
}
} )
}
module.exports = queue