-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
63 lines (47 loc) · 1.5 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
var Events = require('./events');
(function(exports, module, self) {
var S_PENDING = "pending",
S_RESOLVED = "resolved",
S_REJECTED = "rejected";
var Promise = function(fn) {
this.state = S_PENDING;
this.reason = null;
if ( fn ) fn(this.resolve, this.reject);
};
Promise.prototype.then = function(onFulfilled, onRejected) {
var parent = new Promise();
if ( onFulfilled && typeof onFulfilled === "function" ) {
onFulfilled.called = false;
this.on('resolved', parent.resolve.bind(parent));
this.onFulfilled = onFulfilled;
}
if ( onRejected && typeof onRejected === "function" ) {
onRejected.called = false;
this.on('reject', parent.reject.bind(parent));
this.onRejected = onRejected;
}
return parent;
};
Promise.prototype.resolve = function(val) {
if ( this.state === S_PENDING ) {
this.state = S_RESOLVED;
if ( this.onFulfilled && !this.onFulfilled.called )
this.trigger('resolved', this.onFulfilled(val));
}
return this;
};
Promise.prototype.reject = function(reason) {
if ( this.state === S_PENDING ) {
this.state = S_REJECTED;
this.reason = reason;
if ( this.onRejected && !this.onRejected.called )
this.trigger('reject', this.onRejected(reason));
}
return this;
};
Events.extend(Promise.prototype);
if ( typeof exports !== "undefined" )
exports = module.exports = Promise;
else
this.Promise = Promise;
})(exports, module, this);