UNPKG

2.43 kBJavaScriptView Raw
1/*
2 * Very simple "Promise" impl.
3 * <p>
4 * Intentionally not using the "promise" module/polyfill because it will add a few Kb and we
5 * only need something very simple here. We really just want to follow the main pattern
6 * and don't need some of the fancy stuff.
7 * <p>
8 * I think so long as we stick to same interface/interaction pattern as outlined in the link
9 * below, then we can always switch to the "promise" module later without breaking anything.
10 * <p>
11 * See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
12 */
13
14exports.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
24function APromise() {
25 this.state = 'PENDING';
26 this.whenFulfilled = undefined;
27 this.whenRejected = undefined;
28 this.applyFulfillArgs = false;
29}
30
31APromise.prototype.applyArgsOnFulfill = function() {
32 this.applyFulfillArgs = true;
33 return this;
34}
35
36APromise.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 // redefine "onFulfilled" to call immediately
52 this.onFulfilled = function (whenFulfilled) {
53 if (whenFulfilled) {
54 doFulfill(whenFulfilled, result);
55 }
56 return this;
57 }
58};
59
60APromise.prototype.reject = function (reason) {
61 this.state = 'REJECTED';
62 if (this.whenRejected) {
63 this.whenRejected(reason);
64 }
65 // redefine "onRejected" to call immediately
66 this.onRejected = function(whenRejected) {
67 if (whenRejected) {
68 whenRejected(reason);
69 }
70 return this;
71 }
72};
73
74APromise.prototype.onFulfilled = function(whenFulfilled) {
75 if (!whenFulfilled) {
76 throw 'Must provide an "whenFulfilled" callback.';
77 }
78 this.whenFulfilled = whenFulfilled;
79 return this;
80};
81
82APromise.prototype.onRejected = function(whenRejected) {
83 if (whenRejected) {
84 this.whenRejected = whenRejected;
85 }
86 return this;
87};