javascript">function MyPromise(fn) {
pending = '待定';
fulfilled = '成功';
rejected = '失败';
// 定义初始化状态
this.status = pending;
this.res = null;
this.ret = null;
// resolve 时的函数数组
this.resolveCallBack = [];
// reject 时的函数数组
this.rejectCallBack = [];
// 定义 resolve 和 reject 函数
const resolve = (res) => {
setTimeout(() => {
if (this.status === pending) {
// 变更状态
this.status = fulfilled;
// 保存值
this.res = res;
this.resolveCallBack.forEach((callback) => callback(this.res));
}
}, 1000);
};
const reject = (ret) => {
setTimeout(() => {
if (this.status === pending) {
// 变更状态
this.status = rejected;
// 保存值
this.ret = ret;
this.rejectCallBack.forEach((callback) => callback(this.ret));
}
}, 1000);
};
// 因为初始化的时候该函数就被执行了,并且接受两个函数作为参数
// 初始化时如果遇到错误会直接 reject 出去
try {
fn(resolve, reject);
} catch (error) {
reject(error);
}
}
// 定义then方法
MyPromise.prototype.then = function (onFulfilled, onRejected) {
// .then 方法会返回一个新的 Promise 对象
return new MyPromise((resolve, reject) => {
if (this.status === pending) {
// onFulfilled 和 onRejected 是异步完成的,这里只要把函数 push 进去就可以啦
resolve(this.resolveCallBack.push(onFulfilled));
this.rejectCallBack.push(onRejected);
}
if (this.status === fulfilled) {
onFulfilled(this.res);
}
if (this.status === rejected) {
onRejected(this.ret);
}
});
};
//测试
const promise = new MyPromise(function (resolve, reject) {
throw new Error('报错');
reject(3);
console.log(1);
})
.then((res) => {
console.log(res);
}, (ret) => {
console.log(ret);
})
.then((res) => {
console.log(4);
});
console.log(2);
// 最终输出的结果为: 2、报错、4
// 因为直接抛出错误了,所以后面的 reject 和 console 就不会再执行了
还有很多边界条件需要判断和优化的,这里只是简单实现一下