-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsequence.js
43 lines (39 loc) · 897 Bytes
/
sequence.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
/**
* An abstraction around time bound delayed execution of a series of promises.
*/
const {Future} = require('./future');
const assert = require('assert');
class Sequence {
constructor( initialValue = true ) {
const when = new Future();
when.accept(initialValue);
this.last_op = when.promised;
}
next( perform ){
assert.equal(typeof perform, "function");
const operation = this.last_op.then(( input ) => {
return perform( input )
});
this.last_op = operation;
return operation;
}
within_otherwise( timeframe, perform, fail, clock ) {
let canceled = false;
let waiting = true;
const token = clock.notifyIn(timeframe, () =>{
if( waiting ) {
canceled = true;
fail()
}
});
this.next( (input) => {
if( canceled ){ return input; }
waiting = false;
clock.cancel(token);
return perform( input )
});
}
}
module.exports = {
Sequence
};