比如下面这个异步任务,一秒钟以后才会执行 resolve()函数,所以执行 then 方法的时候 PromiseState 还是 pending, 就不会调用 then 方法的两个参数函数
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("ok");
});
}, 1000);
p.then(
(value) => {},
(reason) => {}
);
所以在 then 方法里还需要调用做一个 PromiseState 为 pending 的判断
Promise.prototype.then = function (onResolved, onRejected) {
if (this.PromiseState === "resolved") {
onResolved(this.PromiseResult);
}
if (this.PromiseState === "rejected") {
onRejected(this.PromiseResult);
}
if (this.PromiseState === "pending") {
}
};
判断里面执行什么呢,我们要知道,我们需要在什么时候执行 then 方法
其实是在执行完 resolve() 或者 reject() 以后,获取了状态以后才要去执行 then()里面的 onResolved() 或者 onRejected() 函数
所以我们就需要在 Promise 构造函数里面的 resolve() 和 reject() 函数里面添加一个判断,判断此时是异步任务还是同步任务(也就是说此时 then() 里的 onResolved() 或者 onRejected() 函数是否调用)
做这个判断之前,我们给 Promise 构造函数添加一个属性 callback
function Promise(executor) {
this.PromiseState = "pending";
this.PromiseResult = null;
this.callback = {};
function resolve(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "resolved";
self.PromiseResult = data;
}
function reject(data) {
if (self.PromiseState !== "pending") return;
self.PromiseState = "rejected";
self.PromiseResult = data;
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
然后在 then() 方法里面判断状态为 pending 还未改变的时候,给 callback 属性赋值
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.callback = {
onResolved,
onRejected,
};
}
};
然后在调用完 resolve() 或者 reject() 函数以后,判断callback属性有没有值,有值说明是异步任务,然后在这里调用callback的方法,用这个 callback 属性里面的 then()方法里的回调函数,并传参
function Promise(executor) {
this.PromiseState = "pending";
this.PromiseResult = null;
this.callback = {};
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);
}
}