forked from nodejs/node-v0.x-archive
/
events.js
113 lines (94 loc) · 2.65 KB
/
events.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
(function () {
// node.EventEmitter is defined in src/events.cc
// node.EventEmitter.prototype.emit() is also defined there.
node.EventEmitter.prototype.addListener = function (type, listener) {
if (listener instanceof Function) {
if (!this._events) this._events = {};
if (!this._events.hasOwnProperty(type)) this._events[type] = [];
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit("newListener", type, listener);
this._events[type].push(listener);
}
return this;
};
node.EventEmitter.prototype.listeners = function (type) {
if (!this._events) this._events = {};
if (!this._events.hasOwnProperty(type)) this._events[type] = [];
return this._events[type];
};
node.Promise.prototype.timeout = function(timeout) {
if (timeout === undefined) {
return this._timeoutDuration;
}
this._timeoutDuration = timeout;
if (this._timer) {
clearTimeout(this._timer);
}
var promiseComplete = false;
var onComplete = function() {
promiseComplete = true;
};
this
.addCallback(onComplete)
.addCancelback(onComplete)
.addErrback(onComplete);
var self = this
this._timer = setTimeout(function() {
if (promiseComplete) {
return;
}
self.emitError(new Error('timeout'));
}, this._timeoutDuration);
return this;
};
node.Promise.prototype.cancel = function() {
this._events['success'] = [];
this._events['error'] = [];
this.emitCancel();
};
node.Promise.prototype.emitCancel = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift('cancel');
this.emit.apply(this, args);
};
node.Promise.prototype.addCallback = function (listener) {
this.addListener("success", listener);
return this;
};
node.Promise.prototype.addErrback = function (listener) {
this.addListener("error", listener);
return this;
};
node.Promise.prototype.addCancelback = function (listener) {
this.addListener("cancel", listener);
return this;
};
node.Promise.prototype.wait = function () {
var ret;
var had_error = false;
this.addCallback(function () {
if (arguments.length == 1) {
ret = arguments[0];
} else if (arguments.length > 1) {
ret = [];
for (var i = 0; i < arguments.length; i++) {
ret.push(arguments[i]);
}
}
})
.addErrback(function (arg) {
had_error = true;
ret = arg;
})
.block();
if (had_error) {
if (ret) {
throw ret;
} else {
throw new Error("Promise completed with error (No arguments given.)");
}
}
return ret;
};
})(); // end anonymous namespace