-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpromise-pool.js
58 lines (57 loc) · 2.03 KB
/
promise-pool.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
function promisePool({max_parallel, next_promise, next_promise_data, threads, promises, context_data}) {
var promises_generator = promises || next_promise
var self = {
threads: max_parallel || threads,
started: 0,
ended: 0,
last_started: false,
promises_generator: Array.isArray(promises_generator) ? [...promises_generator] : promises_generator,
next_promise_data: next_promise_data || context_data,
results: []
}
self.live = self.threads
var promise = new Promise(function(resolve, _reject) {
function startNext(self, thread) {
const context = {
index: self.started,
thread,
data: self.next_promise_data,
ended: false
}
let next
if (self.last_started) next = null
else if (promises_generator.next) next = promises_generator.next({ index: self.started, data: self.next_promise_data }).value
else if (Array.isArray(self.promises_generator)) next = self.promises_generator.shift()
else next = self.promises_generator({ index: self.started, data: self.next_promise_data })
if (next && next.then) {
self.started += 1
//console.log('promise ' + JSON.stringify(context))
next.then(function(result) {
context.ended = self.ended
self.ended += 1
//console.log(`promise ${context.index} resolved`)
self.results[context.index] = { context, promise: next, result: result }
startNext(self, thread)
}).catch(function(err) {
context.ended = self.ended
self.ended += 1
//console.log(`promise ${context.index} rejected`)
self.results[context.index] = { context, promise: next, error: err }
startNext(self, thread)
})
} else {
self.last_started = true
self.live -= 1
if (self.live <= 0) {
resolve(self.results)
}
}
}
for (var i=0; i<self.threads; i+=1) {
startNext(self, i)
}
})
promise.poolState = self
return promise
}
module.exports = promisePool