// 核心方法:处理成功或失败执行的返回值,处理promise2的关系;
function resolvePromise(promise2, x, resolve, reject) {
// 有可能x===promise2
if (promise2 === x) {
return reject(new TypeError('TypeError: Chaining cycle detected for promise #<Promise>'));
}
// 如果是第三方的Promise
let called; // 文档要求,一旦成功,不能调用失败
if ((x !== null && typeof x === 'object') || typeof x === 'function') {
// x可能是一个promise
try {
// x = {then:function(){}}
let then = x.then; // 取then方法
if (typeof then === 'function') {
then.call(x, function (y) {
if (!called) { called = true; } else { return; }
resolvePromise(x, y, resolve, reject); // 递归检查promise
}, function (r) {
if (!called) { called = true; } else { return; }
reject(r);
});
} else {
resolve(x); // 普通值
}
} catch (error) {
if (!called) { called = true; } else { return; }
reject(error);
}
} else {
// x是普通值,直接返回
resolve(x);
}
}