Open lewenweijia opened 5 years ago
class Promise {
status = "pending";
value = null;
handlers = [];
constructor(executor) {
try {
executor(this.resolve, this.reject);
} catch (err) {
this.reject(err);
}
}
resolve = res => {
this.status = "fulfilled";
this.value = res;
this.handlers.forEach(this._handle);
};
reject = err => {
this.status = "rejected";
this.value = err;
this.handlers.forEach(this._handle);
};
_handle = handler => {
switch (this.status) {
case "pending":
this.handlers.push(handler);
break;
case "fulfilled":
handler.onFullfilled(this.value);
break;
case "rejected":
handler.onReject(this.value);
break;
}
};
then = (onFullfilled, onReject) => {
return new Promise((resolve, reject) => {
this._handle.push({
onFullfilled: value => void resolve(onFullfilled(value)),
onReject: err => void reject(onReject(err))
});
});
};
}