MyPromise.resolveMyPromise = function(promise2, x, resolve, reject){ // 循环调用 thenable 方法时只调用一次 let called = false;
// 如果返回的 x 等于 promise2,则报错,避免循环调用 if(x===promise2){ return reject(newnewTypeError("cannot return the same promise object from onfulfilled or on rejected callback.")) }
if(x instanceof MyPromise){
} // 避免null也为object elseif( (x!==null && typeof x === "object") || typeof x ==="function"){
MyPromise.resolveMyPromise = function(promise2, x, resolve, reject){ // 循环调用 thenable 方法时只调用一次 let called = false;
// 如果 promise2 和 x 指向同一对象,以 TypeError 为据因拒绝执行 promise if(x===promise2){ reject(newnewTypeError("cannot return the same promise object from onfulfilled or on rejected callback.")) }
// x 为 Promise if(x instanceof MyPromise){ // 如果 x 为 Promise ,则使 promise 接受 x 的状态 // 如果 x 处于执行态,用相同的值执行 promise // 如果 x 处于拒绝态,用相同的据因拒绝 promise x.then(y=>{ MyPromise.resolveMyPromise(promise2, y, resolve, reject); }, r=>{ reject(r); }) } // 如果 x 为对象或者函数 (x !== null 避免null也为object) elseif( (x!==null && typeof x === "object") || typeof x ==="function"){ try{ // 防止调用 then 的 getter 方法调用抛出异常 // 把 x.then 赋值给 then const then = x.then; // 如果 then 是函数,将 x 作为函数的作用域 this 调用之。 // 传递两个回调函数作为参数,第一个参数叫做 resolvePromise ,第二个参数叫做 rejectPromise: if(typeof then === "function"){ then.call(x, y=>{ // 如果 resolvePromise 和 rejectPromise 均被调用, // 或者被同一参数调用了多次,则优先采用首次调用并忽略剩下的调用 if(called) return; called = true; MyPromise.resolveMyPromise(promise2, y, resolve, reject); }, r=>{ if(called) return; called = true; reject(r); }) }else{ if(called) return; called = true; resolve(x); } // }catch(e){ if(called) return; called = true; reject(e); } }else{ // 如果不是 MyPromise 或者不是具有 thenable 的类及方法,就直接传入 x 数据 resolve(x); } }