个人理解: Promise对象接受一个函数作为参数,此函数有两个参数,resolve传入value执行成功回调,reject执行失败回调;then方法则是传入回调函数。
class Promise {
constructor(task) {
if (!(task instanceof Function)) {
throw new Error('Promise need a fucntion as parameter');
}
this.task = task;
// 状态
this.status = 'pending';
this.value = null;
//成功回调队列
this._fulfilledQueues = [];
//失败回调队列
this._rejectedQueues = [];
//执行初始任务
this.task(
this._resolve.bind(this),
this._reject.bind(this)
);
}
_resolve(value) {
const { status } = this;
if (status != 'pending') { return; }
this.status = 'fulfilled';
this.value = value;
// 当this.task为同步任务 settimeout可以将执行指向then
setTimeout(() => {
let fn;
while (fn = this._fulfilledQueues.shift()) {
value = fn(value);
}
});
}
_reject(error) {
const { status } = this;
if (status != 'pending') { return; }
this.status = 'rejected';
this.value = error;
setTimeout(() => {
let fn;
while (fn = this._rejectedQueues.shift()) {
error = fn(error);
}
});
}
then(onFulfilled, onRejected) {
const { status, value } = this;
// 返回pomise: 将返回promise的resolve方法(即触发回调的方法)放到上一个promise的回调当中
return new Promise((resolve, reject) => {
const fulfilledCb = val => {
try {
const rs = onFulfilled(val);
if (rs instanceof Promise) {
rs.then(resolve, reject);
} else {
resolve(rs);
}
} catch (er) {
onRejected(er);
}
};
const rejectedCb = error => {
try {
const rs = onRejected(error);
if (rs instanceof Promise) {
rs.then(resolve, reject);
} else {
reject(rs);
}
} catch (er) {
onRejected(er);
}
};
swith (status) {
case 'pending':
this._fulfilledQueues.push(fulfilledCb);
this._rejectedQueues.push(rejectedCb);
break;
case 'fulfilled':
onFulfilled(value);
break;
case 'rejected':
onRejected(value);
break;
default:
}
});
}
}
网友评论