Promise原始碼實現

wannawanna發表於2018-05-20

Promise原始碼實現

Promise使用

let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('promise')
    }, 1000);
})
promise.then((data) => {
    console.log(data)
}, (err) => {
    console.log(err)
})
複製程式碼

Promise類實現實現

class Promise {
    constructor(executor) {
        // 預設狀態是等待態
        this.status = 'pending';
        this.value = undefined;
        this.reason = undefined;
        // 存放成功的回撥
        this.onResolvedCallbacks = [];
        // 存放失敗的回撥
        this.onRejectedCallbacks = [];
        let resolve = (data) => {
            if (this.status === 'pending') {
                this.value = data;
                this.status = 'resolved';
                this.onResolvedCallbacks.forEach(fn => fn());
            }
        }
        let reject = (reason) => {
            if (this.status === 'pending') {
                this.reason = reason;
                this.status = 'rejected';
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }
        try { // 執行時可能會發生異常
            executor(resolve, reject);
        } catch (e) {
            reject(e); // promise失敗了
        }
    }
}
複製程式碼

Promise原型then方法實現

class Promise {
    constructor(executor) {
        ...
    }
    then(onFulFilled, onRejected) {
        if (this.status === 'resolved') {
            onFulFilled(this.value);
        }
        if (this.status === 'rejected') {
            onRejected(this.reason);
        }
        // 當前既沒有完成 也沒有失敗
        if (this.status === 'pending') {
            // 存放成功的回撥
            this.onResolvedCallbacks.push(() => {
                onFulFilled(this.value);
            });
            // 存放失敗的回撥
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason);
            });
        }
    }
}
複製程式碼
  • then方法可以返回值或者Promise, resolvePromise方法處理
function resolvePromise(promise2, x, resolve, reject) {
  // 判斷x是不是promise
  // 規範裡規定了一段程式碼,這個程式碼可以實現我們的promise和別人的promise可以進行互動
  if (promise2 === x) { // 不能自己等待自己完成
    return reject(new TypeError('迴圈引用'));
  }
  // x不是null或者是物件或者函式
  if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
    let called; // 防止成功後呼叫失敗
    try { // 防止取then是出現異常 Object.defineProperty
      let then = x.then; // 取x的then方法 {then:{}}
      if (typeof then === 'function') { // 如果then是函式我就認為它是promise
        // call 第一個引數是this ,後面的是成功的回撥和失敗的回撥
        then.call(x, y => { // 如果y是promise就繼續遞迴解析promise
          if(called) return;
          called = true;
          resolvePromise(promise2,y,resolve,reject);
        }, r => { // 只要失敗了就失敗了
          if (called) return;
          called = true;
          reject(r);
        });
      }else{ // then是一個普通物件,就直接成功即可1
        resolve(x);
      }
    } catch (e) {
      if (called) return;
      called = true;
      reject(e);
    }
  } else { // x = 123
    resolve(x); // x就是一個普通值
  }
}
class Promise {
  constructor(executor) {
      ...
  }
  then(onFulFilled, onRejected) {
    let promise2;
    if (this.status === 'resolved') {
      promise2 = new Promise((resolve, reject) => {
        // 成功的邏輯 失敗的邏輯
        let x = onFulFilled(this.value);
        // 看x是不是promise 如果是promise 取他的結果 作為promise2,成功的結果
        // 如果要是返回一個普通值 作為promise2,成功的結果

        // resolvePromise可以解析x和promise2之間的關係
        resolvePromise(promise2, x, resolve, reject);
      });
    }
    if (this.status === 'rejected') {
      promise2 = new Promise((resolve, reject) => {
        let x = onRejected(this.reason);
        resolvePromise(promise2, x, resolve, reject)
      });
    }
    // 當前既沒有完成 也沒有失敗
    if (this.status === 'pending') {
      // 存放成功的回撥
      promise2 = new Promise((resolve, reject) => {
        this.onResolvedCallbacks.push(() => {
          let x = onFulFilled(this.value);
          resolvePromise(promise2, x, resolve, reject)
        });
        // 存放失敗的回撥
        this.onRejectedCallbacks.push(() => {
          let x = onRejected(this.reason);
          resolvePromise(promise2, x, resolve, reject);
        });
      })
    }
    return promise2; // 呼叫then後返回一個新的promise
  }
}
複製程式碼
  • then方法穿透的處理
class Promise {
    constructor(executor) {
        ...
    }
    then(onFulFilled, onRejected) {
        onFulFilled = typeof onFulFilled === 'function' ? onFulFilled : y => y;
        onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
        let promise2;
        if (this.status === 'resolved') {
            promise2 = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        let x = onFulFilled(this.value);
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            });
        }
        if (this.status === 'rejected') {
            promise2 = new Promise((resolve, reject) => {
                setTimeout(() => {
                    try {
                        let x = onRejected(this.reason);
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            });
        }
        if (this.status === 'pending') {
            promise2 = new Promise((resolve, reject) => {
                this.onResolvedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onFulFilled(this.value);
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0)
                });
                // 存放失敗的回撥
                this.onRejectedCallbacks.push(() => {
                    setTimeout(() => {
                        try {
                            let x = onRejected(this.reason);
                            resolvePromise(promise2, x, resolve, reject);
                        } catch (e) {
                            reject(e);
                        }
                    }, 0);
                });
            })
        }
        return promise2; // 呼叫then後返回一個新的promise
    }
    // catch接收的引數 只用錯誤
    catch(onRejected) {
        // catch就是then的沒有成功的簡寫
        return this.then(null, onRejected);
    }
}
複製程式碼

Promose靜態方法resolve, reject, all, race實現

Promise.resolve = function (val) {
  return new Promise((resolve, reject) => resolve(val))
}
Promise.reject = function (val) {
  return new Promise((resolve, reject) => reject(val));
}
Promise.race = function (promises) {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < promises.length; i++) {
      promises[i].then(resolve, reject);
    }
  });
}
Promise.all = function (promises) {
  return new Promise((resolve,reject)=>{
    let arr = [];
    let i = 0; // i的目的是為了保證獲取全部成功,來設定的索引
    function processData(index,data) {
      arr[index] = data;
      i++;
      if (i === promises.length){
        resolve(arr);
      }
    }
    for(let i = 0;i<promises.length;i++){
      promises[i].then(data=>{
        processData(i,data);
      }, reject);
    }
  })
}
複製程式碼

Promise原始碼實現大概就這些內容,作為學習的一個記錄,希望對大家有所幫助

相關文章