1、构造函数实现
function Promise(executor) {
// 添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
const self = this;
let resolve = function (data) {
// 判断状态
if (self.PromiseState !== 'pending') return
//修改状态,设置对象值
self.PromiseState = 'fulfilled';
self.PromiseResult = data;
};
let reject = function (data) {
// 判断状态
if (self.PromiseState !== 'pending') return
//修改状态,设置对象值
self.PromiseState = 'rejected';
self.PromiseResult = data;
};
try {
// 同步调用 执行器函数
executor(resolve, reject);
} catch (e) {
reject(e)
}
}
// 添加.then方法
Promise.prototype.then = function (onResolve, onReject) {
//调用回掉函数
if (this.PromiseState === 'fulfilled') {
onResolve(this.PromiseResult)
}
if (this.PromiseState === 'rejected') {
onReject(this.PromiseResult)
}
}
2、类实现
class Promise {
constructor(executor) {
// 添加属性
this.PromiseState = 'pending';
this.PromiseResult = null;
const self = this;
let resolve = function (data) {
// 判断状态
if (self.PromiseState !== 'pending') return
//修改状态,设置对象值
self.PromiseState = 'fulfilled';
self.PromiseResult = data;
};
let reject = function (data) {
// 判断状态
if (self.PromiseState !== 'pending') return
//修改状态,设置对象值
self.PromiseState = 'rejected';
self.PromiseResult = data;
};
try {
// 同步调用 执行器函数
executor(resolve, reject);
} catch (e) {
reject(e)
}
};
/// 添加.then方法
then = function (onResolve, onReject) {
//调用回掉函数
if (this.PromiseState === 'fulfilled') {
onResolve(this.PromiseResult)
}
if (this.PromiseState === 'rejected') {
onReject(this.PromiseResult)
}
}
}