2 module.exports = function(Promise, INTERNAL) {
3 var util = require("./util");
4 var errorObj = util.errorObj;
5 var isObject = util.isObject;
7 function tryConvertToPromise(obj, context) {
9 if (obj instanceof Promise) return obj;
10 var then = getThen(obj);
11 if (then === errorObj) {
12 if (context) context._pushContext();
13 var ret = Promise.reject(then.e);
14 if (context) context._popContext();
16 } else if (typeof then === "function") {
17 if (isAnyBluebirdPromise(obj)) {
18 var ret = new Promise(INTERNAL);
28 return doThenable(obj, then, context);
34 function doGetThen(obj) {
38 function getThen(obj) {
40 return doGetThen(obj);
47 var hasProp = {}.hasOwnProperty;
48 function isAnyBluebirdPromise(obj) {
49 return hasProp.call(obj, "_promise0");
52 function doThenable(x, then, context) {
53 var promise = new Promise(INTERNAL);
55 if (context) context._pushContext();
56 promise._captureStackTrace();
57 if (context) context._popContext();
58 var synchronous = true;
59 var result = util.tryCatch(then).call(x, resolve, reject);
62 if (promise && result === errorObj) {
63 promise._rejectCallback(result.e, true, true);
67 function resolve(value) {
69 promise._resolveCallback(value);
73 function reject(reason) {
75 promise._rejectCallback(reason, synchronous, true);
81 return tryConvertToPromise;