eadfffb59d76f4f6520b1b20ad5cb8a0c963c44d
[aai/esr-gui.git] /
1 "use strict";
2 module.exports = function(Promise, INTERNAL) {
3 var util = require("./util.js");
4 var errorObj = util.errorObj;
5 var isObject = util.isObject;
6
7 function tryConvertToPromise(obj, context) {
8     if (isObject(obj)) {
9         if (obj instanceof Promise) {
10             return obj;
11         }
12         else if (isAnyBluebirdPromise(obj)) {
13             var ret = new Promise(INTERNAL);
14             obj._then(
15                 ret._fulfillUnchecked,
16                 ret._rejectUncheckedCheckError,
17                 ret._progressUnchecked,
18                 ret,
19                 null
20             );
21             return ret;
22         }
23         var then = util.tryCatch(getThen)(obj);
24         if (then === errorObj) {
25             if (context) context._pushContext();
26             var ret = Promise.reject(then.e);
27             if (context) context._popContext();
28             return ret;
29         } else if (typeof then === "function") {
30             return doThenable(obj, then, context);
31         }
32     }
33     return obj;
34 }
35
36 function getThen(obj) {
37     return obj.then;
38 }
39
40 var hasProp = {}.hasOwnProperty;
41 function isAnyBluebirdPromise(obj) {
42     return hasProp.call(obj, "_promise0");
43 }
44
45 function doThenable(x, then, context) {
46     var promise = new Promise(INTERNAL);
47     var ret = promise;
48     if (context) context._pushContext();
49     promise._captureStackTrace();
50     if (context) context._popContext();
51     var synchronous = true;
52     var result = util.tryCatch(then).call(x,
53                                         resolveFromThenable,
54                                         rejectFromThenable,
55                                         progressFromThenable);
56     synchronous = false;
57     if (promise && result === errorObj) {
58         promise._rejectCallback(result.e, true, true);
59         promise = null;
60     }
61
62     function resolveFromThenable(value) {
63         if (!promise) return;
64         promise._resolveCallback(value);
65         promise = null;
66     }
67
68     function rejectFromThenable(reason) {
69         if (!promise) return;
70         promise._rejectCallback(reason, synchronous, true);
71         promise = null;
72     }
73
74     function progressFromThenable(value) {
75         if (!promise) return;
76         if (typeof promise._progress === "function") {
77             promise._progress(value);
78         }
79     }
80     return ret;
81 }
82
83 return tryConvertToPromise;
84 };