直接上代码
class myPromise {
// 创建myPromise实例时接收fn
constructor(fn) {
this.thencallback = [];
this.catchcallback = [];
this.value = null;
this.error = null;
this.state = 'pending';
// 设置传入的返回值并将状态置为已完成
const resolve = res => {
this.value = res;
this.state = 'fulfilled';
this.thencallback.forEach(v => v(res));
};
// 设置传入的返回值并将状态置为失败
const reject = err => {
this.error = err;
this.state = 'rejected';
this.catchcallback.forEach(v => v(...err));
};
// 执行fn并传入resolve和reject方法,如果捕获到异常则执行reject
try {
fn(resolve, reject);
} catch (error) {
reject(error);
}
}
// 接收rs和rj两个fn
then(rs, rj) {
const _this = this;