// 表示状态,便于后期维护
const PENDING = 'pending';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';
function MyPromise(fn) {
// 因代码可能会异步执行,用于获取正确的this对象
const that = this;
// 初始状态为pending
that.state = PENDING;
// 用于保存resolve 或者 reject 中传入的值
that.value = null;
// 用于保存then中的回调,因为当执行完Promise时状态可能还是等待中,
// 这时候应该把then中的回调保存起来用户状态改变时使用
that.resolvedCallbacks = [];
that.rejectedCallbacks = [];
// 首先两个函数都得判断当前状态是否是等待中,因为只有等待状态可以改变状态
// 将当前状态更改为对应状态,并且将传入的值赋值给value
// 遍历回调数组并执行
function resolve(value) {
if(that.state === PENDING) {
that.state = RESOLVED;
that.value = value;
that.resolvedCallbacks.map(cb => cb(that.value));
}
}
function reject(value) {
if(that.state === PENDING) {
that.state = REJECTED;
that.value = value;
that.rejectedCallbacks.map(cb => cb(that.value));
}
}
// 执行传入的参数并且将之前的两个函数当做参数传进去
// 注意: 可能执行函数过程中会遇到错误,需要捕获错误并执行reject函数
try{
fn(resolve, reject)
} catch (e) {
reject(e);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
const that = this;
// 首先判断两个参数是否为函数类型,因为这两个参数时可选参数
// 当参数不是函数类型时,需要创建一个函数赋值给对应的参数,同时也实现了透传
// eg: Promise.resolve(4).then().then(value => console.log(value))
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r; };
// 判断状态
// 当状态不是等待态时,就去执行相应的函数。
// 如果状态是等待态的话,就往回调函数中push函数
if(that.state === PENDING) {
that.resolvedCallbacks.push(onFulfilled);
that.rejectedCallbacks.push(onRejected);
}
if(that.state === RESOLVED) {
onFulfilled(that.value);
}
if(that.state === REJECTED) {
onRejected(that.value)
}
};
eg:
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 0)
}).then(value => {
console.log(value)
});