Promise 實作

實作 Promise

在實作 Promise 中首先面對的問題

  1. 同步動作時會設定好 resolve 後執行

  2. then catch 鏈式結構

  3. function 執行和參數傳遞處理

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 執行和參數傳遞處理

  1. resolve 不執行 2 次

  2. executor 中出現 error

  3. catch function

  4. 靜態方法 resolve reject

  5. then 中出現 error

  6. 鏈式結構中傳遞參數

  7. then 中回傳 promise

  8. promise 特別行為

到目前為止的程式

  1. then 中出現 error

  1. 鏈式結構中傳遞參數

  1. then 中回傳 promise

  1. promise 特別行為

完成版

Last updated