1. 程式人生 > 其它 >用 class 手寫一個 Promise

用 class 手寫一個 Promise

class Promise {
constructor(executer) { //建構函式 constructor 裡面是個執行器
this.status = 'pending'; //預設的狀態 pending
this.value = undefined //成功的值預設 undefined
this.reason = undefined //失敗的值預設 undefined
//狀態只有在 pending 時候才能改變
let resolveFn = value=>{
//判斷只有等待時才能 resolve 成功
if (this.status == 'pending') {
this.status = 'resolve';
this.value = value;
}
}
//判斷只有等待時才能 reject 失敗
let rejectFn = reason=>{
if (this.status == 'pending') {
this.status = 'reject';
this.reason = reason;
}
}
try {
//把 resolve 和 reject 兩個函式傳給執行器 executer
executer(resolveFn, rejectFn);
} catch(e) {
rejectFn(e); //失敗的話進 catch
}
}
then(onFufilled, onReject) {
//如果狀態成功呼叫 onFufilled
if (this.status = 'resolve') {
onFufilled(this.value);
}
//如果狀態失敗呼叫 onReject
if (this.status = 'reject') {
onReject(this.reason);
}
}
}