forked from postwait/node-amqp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
promise.js
86 lines (67 loc) · 1.99 KB
/
promise.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
var events = require('events');
var inherits = require('sys').inherits;
exports.Promise = function () {
events.EventEmitter.call(this);
this._blocking = false;
this.hasFired = false;
this._values = undefined;
};
inherits(exports.Promise, events.EventEmitter);
exports.Promise.prototype.timeout = function(timeout) {
if (!timeout) {
return this._timeoutDuration;
}
this._timeoutDuration = timeout;
if (this.hasFired) return;
this._clearTimeout();
var self = this;
this._timer = setTimeout(function() {
self._timer = null;
if (self.hasFired) {
return;
}
self.emitError(new Error('timeout'));
}, timeout);
return this;
};
exports.Promise.prototype._clearTimeout = function() {
if (!this._timer) return;
clearTimeout(this._timer);
this._timer = null;
}
exports.Promise.prototype.emitSuccess = function() {
if (this.hasFired) return;
this.hasFired = 'success';
this._clearTimeout();
this._values = Array.prototype.slice.call(arguments);
this.emit.apply(this, ['success'].concat(this._values));
};
exports.Promise.prototype.emitError = function() {
if (this.hasFired) return;
this.hasFired = 'error';
this._clearTimeout();
this._values = Array.prototype.slice.call(arguments);
this.emit.apply(this, ['error'].concat(this._values));
if (this.listeners('error').length == 0) {
var self = this;
process.nextTick(function() {
if (self.listeners('error').length == 0) {
throw (self._values[0] instanceof Error)
? self._values[0]
: new Error('Unhandled emitError: '+JSON.stringify(self._values));
}
});
}
};
exports.Promise.prototype.addCallback = function (listener) {
if (this.hasFired === 'success') {
listener.apply(this, this._values);
}
return this.addListener("success", listener);
};
exports.Promise.prototype.addErrback = function (listener) {
if (this.hasFired === 'error') {
listener.apply(this, this._values);
}
return this.addListener("error", listener);
};