receiver.js
1.1 KB
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
59
60
61
62
63
/**
* Expose `Receiver`.
*/
module.exports = Receiver
/**
* Initialize a `Receiver`.
*
* @param {Mixed} val
* @api private
*/
function Receiver(val) {
this.val = val
this.isAdded = false
this.err = null
this.cb = null
this.isDone = false
}
/**
* Call the callback if the pending add is complete.
*
* @api private
*/
Receiver.prototype.attemptNotify = function () {
if ((this.isAdded || this.err) && this.cb && !this.isDone) {
this.isDone = true
setImmediate(function () { this.cb(this.err) }.bind(this))
}
}
/**
* Reject the pending add with an error.
*
* @param {Error} err
* @api private
*/
Receiver.prototype.error = function (err) {
this.err = err
this.attemptNotify()
}
/**
* Get the `val` and set the state of the value to added
*
* @return {Mixed} val
* @api private
*/
Receiver.prototype.add = function () {
this.isAdded = true
this.attemptNotify()
return this.val
}
/**
* Register the callback.
*
* @api private
*/
Receiver.prototype.callback = function (cb) {
this.cb = cb
this.attemptNotify()
}