c9342bcf23d9bb5cc6bb481bccdd619787bf397a
[aai/esr-gui.git] /
1 "use strict";
2 module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
3 var util = require("./util.js");
4 var isPrimitive = util.isPrimitive;
5 var thrower = util.thrower;
6
7 function returnThis() {
8     return this;
9 }
10 function throwThis() {
11     throw this;
12 }
13 function return$(r) {
14     return function() {
15         return r;
16     };
17 }
18 function throw$(r) {
19     return function() {
20         throw r;
21     };
22 }
23 function promisedFinally(ret, reasonOrValue, isFulfilled) {
24     var then;
25     if (isPrimitive(reasonOrValue)) {
26         then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
27     } else {
28         then = isFulfilled ? returnThis : throwThis;
29     }
30     return ret._then(then, thrower, undefined, reasonOrValue, undefined);
31 }
32
33 function finallyHandler(reasonOrValue) {
34     var promise = this.promise;
35     var handler = this.handler;
36
37     var ret = promise._isBound()
38                     ? handler.call(promise._boundValue())
39                     : handler();
40
41     if (ret !== undefined) {
42         var maybePromise = tryConvertToPromise(ret, promise);
43         if (maybePromise instanceof Promise) {
44             maybePromise = maybePromise._target();
45             return promisedFinally(maybePromise, reasonOrValue,
46                                     promise.isFulfilled());
47         }
48     }
49
50     if (promise.isRejected()) {
51         NEXT_FILTER.e = reasonOrValue;
52         return NEXT_FILTER;
53     } else {
54         return reasonOrValue;
55     }
56 }
57
58 function tapHandler(value) {
59     var promise = this.promise;
60     var handler = this.handler;
61
62     var ret = promise._isBound()
63                     ? handler.call(promise._boundValue(), value)
64                     : handler(value);
65
66     if (ret !== undefined) {
67         var maybePromise = tryConvertToPromise(ret, promise);
68         if (maybePromise instanceof Promise) {
69             maybePromise = maybePromise._target();
70             return promisedFinally(maybePromise, value, true);
71         }
72     }
73     return value;
74 }
75
76 Promise.prototype._passThroughHandler = function (handler, isFinally) {
77     if (typeof handler !== "function") return this.then();
78
79     var promiseAndHandler = {
80         promise: this,
81         handler: handler
82     };
83
84     return this._then(
85             isFinally ? finallyHandler : tapHandler,
86             isFinally ? finallyHandler : undefined, undefined,
87             promiseAndHandler, undefined);
88 };
89
90 Promise.prototype.lastly =
91 Promise.prototype["finally"] = function (handler) {
92     return this._passThroughHandler(handler, true);
93 };
94
95 Promise.prototype.tap = function (handler) {
96     return this._passThroughHandler(handler, false);
97 };
98 };