Deferred.js
1001 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
45
46
47
48
49
"use strict";
/**
* This is apparently a bit like a Jquery deferred, hence the name
*/
class Deferred {
constructor(Promise) {
this._state = Deferred.PENDING;
this._resolve = undefined;
this._reject = undefined;
this._promise = new Promise((resolve, reject) => {
this._resolve = resolve;
this._reject = reject;
});
}
get state() {
return this._state;
}
get promise() {
return this._promise;
}
reject(reason) {
if (this._state !== Deferred.PENDING) {
return;
}
this._state = Deferred.REJECTED;
this._reject(reason);
}
resolve(value) {
if (this._state !== Deferred.PENDING) {
return;
}
this._state = Deferred.FULFILLED;
this._resolve(value);
}
}
// TODO: should these really live here? or be a seperate 'state' enum
Deferred.PENDING = "PENDING";
Deferred.FULFILLED = "FULFILLED";
Deferred.REJECTED = "REJECTED";
module.exports = Deferred;