Version 1
[yaffs-website] / node_modules / bluebird / js / release / thenables.js
1 "use strict";
2 module.exports = function(Promise, INTERNAL) {
3 var util = require("./util");
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) 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();
15             return ret;
16         } else if (typeof then === "function") {
17             if (isAnyBluebirdPromise(obj)) {
18                 var ret = new Promise(INTERNAL);
19                 obj._then(
20                     ret._fulfill,
21                     ret._reject,
22                     undefined,
23                     ret,
24                     null
25                 );
26                 return ret;
27             }
28             return doThenable(obj, then, context);
29         }
30     }
31     return obj;
32 }
33
34 function doGetThen(obj) {
35     return obj.then;
36 }
37
38 function getThen(obj) {
39     try {
40         return doGetThen(obj);
41     } catch (e) {
42         errorObj.e = e;
43         return errorObj;
44     }
45 }
46
47 var hasProp = {}.hasOwnProperty;
48 function isAnyBluebirdPromise(obj) {
49     return hasProp.call(obj, "_promise0");
50 }
51
52 function doThenable(x, then, context) {
53     var promise = new Promise(INTERNAL);
54     var ret = promise;
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);
60     synchronous = false;
61
62     if (promise && result === errorObj) {
63         promise._rejectCallback(result.e, true, true);
64         promise = null;
65     }
66
67     function resolve(value) {
68         if (!promise) return;
69         promise._resolveCallback(value);
70         promise = null;
71     }
72
73     function reject(reason) {
74         if (!promise) return;
75         promise._rejectCallback(reason, synchronous, true);
76         promise = null;
77     }
78     return ret;
79 }
80
81 return tryConvertToPromise;
82 };