-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleCommandQueue.js
41 lines (31 loc) · 1016 Bytes
/
SimpleCommandQueue.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
//
// Async command queue. Enqueue a task & get a promise. Basically works by
// stacking promises on top of each other, beginning with an already resolved
// one.
//
class SimpleCommandQueue {
constructor( nextProcessor ) {
this.nextProcessor = nextProcessor
this.lastPromise = Promise.resolve( {} )
}
process( command ) {
let commandExecutedPromise = new Promise( ( resolveFn, rejectFn ) => {
let processAndResolve = () => {
this.nextProcessor.process( command ).then(
result => resolveFn( result ),
error => rejectFn( error )
)
}
this.lastPromise.then(
processAndResolve,
processAndResolve
)
} )
// NOTE: this relies on the fact that Promise's executor executes
// immediately (which is guaranteed, I guess), otherwise lastPromise value
// would already have changed.
this.lastPromise = commandExecutedPromise
return commandExecutedPromise
}
}
module.exports = SimpleCommandQueue