- 1.Promise本身就是一个构造函数,用来初始化promise实例
- 2.传入一个执行器,内部注册两个方法resolve,reject,最后通过执行器来执行这两个方法
- 3.promise 内部有3个状态 等待状态pedding,成功状态resolved,失败状态rejected
- 4.resolve和reject两个方法就是用来改变status状态得
- 5.后面封装then方法得时候,就是根据当前得状态来判断执行对应方法,第一个方法固定式成功回调,第二个就是失败回调
function Promise(executor) {
//executor执行器
let self = this;
self.status = "pending"; //等待态
self.value = undefined; // 表示当前成功的值
self.reason = undefined; // 表示是失败的值
function resolve(value) {
// 成功的方法
if (self.status === "pending") {
self.status = "resolved";
self.value = value;
}
}
function reject(reason) {
//失败的方法
if (self.status === "pending") {
self.status = "rejected";
self.reason = reason;
}
}
executor(resolve, reject);
}
Promise.prototype.then = function (onFufiled, onRejected) {
let self = this;
if (self.status === "resolved") {
onFufiled(self.value);
}
if (self.status === "rejected") {
onRejected(self.reason);
}
};
module.exports = Promise;