异步的时候指定多个回调函数,比如下面这样
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("ok");
}, 1000);
});
p.then(
(value) => {
console.log(value);
},
(reason) => {
console.log(reason);
}
);
p.then(
(value) => {
alert(value);
},
(reason) => {
alert(reason);
}
);
此时只会执行最后一个回调,也就是 alert
因为两个 p.then 都走了 PromiseState === "pending" 这个判断,第一个 p.then 把 callback 赋值了以后, 第二个 p.then 也给 callback 赋值了,就直接把 callback 给覆盖了,所以就只执行了最后一个回调
所以我们需要把这些回调都保存起来而不是只保存一个,所以 callback 改为 callbacks 变成一个数组
function Promise(executor) {
this.PromiseState = "pending";
this.PromiseResult = null;
this.callbacks = [];
function resolve(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "resolved";
self.PromiseResult = data;
if (self.callback.onResolved) {
self.callback.onResolved(self.PromiseResult);
}
}
function reject(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "rejected";
self.PromiseResult = data;
if (self.callback.onRejected) {
self.callback.onRejected(self.PromiseResult);
}
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
然后 then 方法里面 直接 push
Promise.prototype.then = function (onResolved, onRejected) {
if (this.PromiseState === "resolved") {
onResolved(this.PromiseResult);
}
if (this.PromiseState === "rejected") {
onRejected(this.PromiseResult);
}
if (this.PromiseState === "pending") {
this.callbacks.push({
onResolved,
onRejected,
});
}
};
所以 Promise 里面执行完 resolve() 或者 reject() 以后的代码也得改变
function Promise(executor) {
this.PromiseState = "pending";
this.PromiseResult = null;
this.callbacks = [];
function resolve(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "resolved";
self.PromiseResult = data;
self.callbacks.forEach((item) => {
item.onResolved(self.PromiseResult);
});
}
function reject(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "rejected";
self.PromiseResult = data;
self.callbacks.forEach((item) => {
item.onRejected(self.PromiseResult);
});
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}