/
ListPromise.js
47 lines (46 loc) · 1.09 KB
/
ListPromise.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
44
45
46
47
var proto = require('./proto'),
bind = require('./bind')
module.exports = proto(null,
function(waitForNum, callback) {
this._waitingFor = waitForNum
this._callbacks = []
this._results = []
this._error = null
if (callback) { this.add(callback) }
}, {
add: function(callback) {
if (!this._waitingFor) {
this._notify(callback)
} else {
this._callbacks.push(callback)
}
},
getResponder: function() {
return bind(this, function(err, res) {
if (err) { this.fail(err) }
else { this.fulfill(res) }
})
},
fulfill: function(result) {
if (!this._waitingFor) { throw new Error('ListPromise fulfilled too many times') }
this._results.push(result)
if (!--this._waitingFor) {
this._notifyAll()
}
},
fail: function(error) {
this._error = error
this._notifyAll()
},
_notifyAll: function() {
if (!this._callbacks) { return }
for (var i=0; i<this._callbacks.length; i++) {
this._notify(this._callbacks[i])
}
this._callbacks = null
},
_notify: function(callback) {
callback(this._error, !this._error && this._results)
}
}
)