Promise 實作
實作 Promise
1. 同步動作時會設定好 resolve 後執行
範例:
const b = new Promise((resolve) => {
console.log('hi')
resolve(5)
});
b.then((value) => {
console.log(value)
});
在一般情況下 出現 hi 後就會立即執行 resolve
根本等不到 then 的 function
這種時候就要使用一個 js api
queueMicrotask
這個 api 會將執行動作放入 micro task 中執行
class APromise {
constructor(executor) {
executor(this.resolveFunc.bind(this), this.rejectFunc.bind(this));
}
resolveFunc(value) {
this.resolveValue = value;
queueMicrotask(() => {
this.onFulfilled(value);
})
}
rejectFunc(value) {
this.rejectValue = value;
queueMicrotask(() => {
this.onRejected(value);
})
}
then(onFulfilled = undefined, onRejected = undefined) {
this.onFulfilled = onFulfilled;
this.onRejected = onRejected;
}
}
在這個queueMicrotask中的行為
會進入到 microtaskqueue 中
程式會先完成同步的部分
再從 microtaskqueue 取得需要執行的部分
這時套用第一個範例
output:
hi
5
2. then catch 鏈式結構
3. function 執行和參數傳遞處理
完成版
Last updated