2 module.exports = function(Promise, INTERNAL) {
3 var util = require("./util.js");
4 var errorObj = util.errorObj;
5 var isObject = util.isObject;
7 function tryConvertToPromise(obj, context) {
9 if (obj instanceof Promise) {
12 else if (isAnyBluebirdPromise(obj)) {
13 var ret = new Promise(INTERNAL);
15 ret._fulfillUnchecked,
16 ret._rejectUncheckedCheckError,
17 ret._progressUnchecked,
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();
29 } else if (typeof then === "function") {
30 return doThenable(obj, then, context);
36 function getThen(obj) {
40 var hasProp = {}.hasOwnProperty;
41 function isAnyBluebirdPromise(obj) {
42 return hasProp.call(obj, "_promise0");
45 function doThenable(x, then, context) {
46 var promise = new Promise(INTERNAL);
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,
55 progressFromThenable);
57 if (promise && result === errorObj) {
58 promise._rejectCallback(result.e, true, true);
62 function resolveFromThenable(value) {
64 promise._resolveCallback(value);
68 function rejectFromThenable(reason) {
70 promise._rejectCallback(reason, synchronous, true);
74 function progressFromThenable(value) {
76 if (typeof promise._progress === "function") {
77 promise._progress(value);
83 return tryConvertToPromise;