-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallel.coffee
More file actions
44 lines (36 loc) · 928 Bytes
/
Parallel.coffee
File metadata and controls
44 lines (36 loc) · 928 Bytes
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
{Logger} = require('@coffee-toolbox/logger')
EventEmitter = require('@coffee-toolbox/eventemitter')
SEQUENTIAL = 1
export default class Parallel extends EventEmitter
constructor: (@parallel)->
super()
@logger = new Logger @constructor.name
@semaphore = 1
@queue = []
@concurrency ?= SEQUENTIAL
@logger.assert @concurrency > 0, '@concurrency is not larger than 0'
add: (f)->
@logger.assert f instanceof Function
@logger.assert @semaphore isnt 0, 'adding to an "all-done" Parallel"'
@semaphore += 1
@queue.push @_run_next f
if @semaphore - 1 <= @concurrency
@queue.shift()()
this
allDone: ->
@semaphore -= 1
if @semaphore is 0
Promise.resolve()
else
new Promise (res)=>
@once 'ALLDONE', ->
res()
_run_next: (f)->
=>
Promise.resolve(f())
.then =>
@semaphore -= 1
if @queue.length > 0
@queue.shift()()
else if @semaphore is 0
@emit 'ALLDONE'