1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | exports.make = function(executor) {
|
15 | var thePromise = new APromise();
|
16 | executor.call(thePromise, function(result) {
|
17 | thePromise.resolve(result);
|
18 | }, function(reason) {
|
19 | thePromise.reject(reason);
|
20 | });
|
21 | return thePromise;
|
22 | };
|
23 |
|
24 | function APromise() {
|
25 | this.state = 'PENDING';
|
26 | this.whenFulfilled = undefined;
|
27 | this.whenRejected = undefined;
|
28 | this.applyFulfillArgs = false;
|
29 | }
|
30 |
|
31 | APromise.prototype.applyArgsOnFulfill = function() {
|
32 | this.applyFulfillArgs = true;
|
33 | return this;
|
34 | }
|
35 |
|
36 | APromise.prototype.resolve = function (result) {
|
37 | this.state = 'FULFILLED';
|
38 |
|
39 | var thePromise = this;
|
40 | function doFulfill(whenFulfilled, result) {
|
41 | if (thePromise.applyFulfillArgs) {
|
42 | whenFulfilled.apply(whenFulfilled, result);
|
43 | } else {
|
44 | whenFulfilled(result);
|
45 | }
|
46 | }
|
47 |
|
48 | if (this.whenFulfilled) {
|
49 | doFulfill(this.whenFulfilled, result);
|
50 | }
|
51 |
|
52 | this.onFulfilled = function (whenFulfilled) {
|
53 | if (whenFulfilled) {
|
54 | doFulfill(whenFulfilled, result);
|
55 | }
|
56 | return this;
|
57 | }
|
58 | };
|
59 |
|
60 | APromise.prototype.reject = function (reason) {
|
61 | this.state = 'REJECTED';
|
62 | if (this.whenRejected) {
|
63 | this.whenRejected(reason);
|
64 | }
|
65 |
|
66 | this.onRejected = function(whenRejected) {
|
67 | if (whenRejected) {
|
68 | whenRejected(reason);
|
69 | }
|
70 | return this;
|
71 | }
|
72 | };
|
73 |
|
74 | APromise.prototype.onFulfilled = function(whenFulfilled) {
|
75 | if (!whenFulfilled) {
|
76 | throw 'Must provide an "whenFulfilled" callback.';
|
77 | }
|
78 | this.whenFulfilled = whenFulfilled;
|
79 | return this;
|
80 | };
|
81 |
|
82 | APromise.prototype.onRejected = function(whenRejected) {
|
83 | if (whenRejected) {
|
84 | this.whenRejected = whenRejected;
|
85 | }
|
86 | return this;
|
87 | };
|