写在开头:如果被大佬们看到了有错误还请斧正,如果把萌新带到了沟里,你在爬出来就好了(手动滑稽)
then 方法的多次、链式调用已经完成了,在链式调用 then 方法的时候,then 方法的返回中可以返回 Promise 对象,但是当前的 then 方法是不能够返回当前这个 then 方法返回的对象的,既自己不能返回自己(嗯~不能和自己玩)如果返回了自己是会报错的,因为此时发生了 Promise 的循环调用。
所以接下来继续完善 Promise 让 myPromise 也能在发生循环调用的时候报错,既然是在 then 方法中进行报错提醒那么就应该改造 then 方法。
thenPromise 是被返回的 Promise 对象,x 是成功/失败回调返回的 Promise 对象,那么如果这两个值是相同的也就意味着自己返回了自己。
argParsing() 函数原本就是用来判断 Promise 对象的,所以在这里进行判断
function argParsing(thenPromise, x, resolve, reject) {
if (thenPromise === x) {
reject(new TypeError('Promise 被循环调用了'));
return;
}
if (x instanceof myPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
}
所以在调用 argParsing 的地方也得修改一下
argParsing(thenPromise, x, resolve, reject);
新的问题又出现了:argParsing() 里面传递的 thenPromise 是 myPromise 执行完成之后的结果,然而这里的传递是在 myPromise 执行的过程中就需要得到它,显然目前的代码是不能够满足这样的需求的,因为此时完全就获取不到 thenPromise(好家伙,又白给)
那如果将 argParsing() 放在异步中执行,在执行完 myPromise 之后再执行 argParsing() 就可以得到 thenPromise 了
then(successCallback, failCallback) {
let thenPromise = new myPromise((resolve, reject) => {
if (this.status === FULFILLED) {
setTimeout(() => {
let x = successCallback(this.value);
argParsing(thenPromise, x, resolve, reject);
}, 0);
} else if (this.status === REJECTED) {
setTimeout(() => {
let x = failCallback(this.reason);
argParsing(thenPromise, x, resolve, reject);
}, 0);
} else {
this.successCallback.push(successCallback);
this.failCallback.push(failCallback);
}
});
return thenPromise;
}
运行起来,康康好不好使
到目前为止就实现了 then 方法在链式调用中如何判断 Promise 是不是返回了自己。