Files
biomedjs/node_modules/bluebird/js/release/thenables.js

83 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2015-04-20 05:31:12 -04:00
"use strict";
module.exports = function(Promise, INTERNAL) {
2015-12-16 09:12:35 -08:00
var util = require("./util");
2015-04-20 05:31:12 -04:00
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
2015-12-16 09:12:35 -08:00
if (obj instanceof Promise) return obj;
var then = getThen(obj);
2015-04-20 05:31:12 -04:00
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
2015-12-16 09:12:35 -08:00
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
2015-04-20 05:31:12 -04:00
return doThenable(obj, then, context);
}
}
return obj;
}
2015-12-16 09:12:35 -08:00
function doGetThen(obj) {
2015-04-20 05:31:12 -04:00
return obj.then;
}
2015-12-16 09:12:35 -08:00
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
2015-04-20 05:31:12 -04:00
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
2015-12-16 09:12:35 -08:00
var result = util.tryCatch(then).call(x, resolve, reject);
2015-04-20 05:31:12 -04:00
synchronous = false;
2015-12-16 09:12:35 -08:00
2015-04-20 05:31:12 -04:00
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
2015-12-16 09:12:35 -08:00
function resolve(value) {
2015-04-20 05:31:12 -04:00
if (!promise) return;
2015-12-16 09:12:35 -08:00
promise._resolveCallback(value);
2015-04-20 05:31:12 -04:00
promise = null;
}
2015-12-16 09:12:35 -08:00
function reject(reason) {
2015-04-20 05:31:12 -04:00
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};