promise

92 阅读1分钟
resolvePromise(promise2, x, resolve, reject) {
    let called = false; // 避免多次调用
    if (promise2 === x) {
      return reject(new TypeError('循环引用'));
    } else if (x != null && ((typeof x === 'object') || (typeof x === 'function'))) {
      try { // 是否是thenable对象(具有then方法的对象/函数)
        let then = x.then;
        if (typeof then === 'function') {
          then.call(x, y => {
            if (called) return;
            called = true;
            resolvePromise(promise2, y, resolve, reject);
          }, r => {
            if (called) return;
            called = true;
            reject(r);
          })
        } else { // 说明是一个普通对象/函数
          resolve(x);
        }
      } catch (e) {
        if (called) return;
        called = true;
        reject(e);
      }
    } else {
      resolve(x);
    }
  }
  then(onFulfilled, onReject) {
    onFulfilled =
      typeof onFulfilled === "function" ? onFulfilled : value => value;
    onRejected =
      typeof onRejected === "function" ? onRejected : reason => {
        throw reason;
      };
    let promise2 = new Promise((resolve, reject) => {
      if (this.PromiseState === FULFFILLED) {
        try {
          setTimeout(() => {
            let x = onFulfilled(this.PromiseResult)
            resolvePromise(promise2, x, resolve, reject)
          }, 0);
        } catch (e) {
          reject(e)
        }
      } else if (this.PromiseState === REJECTED) {
        try {
          setTimeout(() => {
            let x = onFulfilled(this.PromiseResult)
            resolvePromise(promise2, x, resolve, reject)
          }, 0);
        } catch (e) {
          reject(e)
        }
      } else if (this.PromiseState === PENDING) {
        this.onFulfilledCallbacks.push((value) => {
          try {
            let x = onFulfilled(value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        })
        this.onRejectedCallbacks.push((value) => {
          try {
            let x = onReject(value)
            resolvePromise(promise2, x, resolve, reject)
          } catch (e) {
            reject(e)
          }
        })
      }


    })
    return promise2
  }