Js实现Promise(符合Promise/A+规范)

// 手写promise
      function Promise(executor) {
        var _this = this
        this.state = 'pending'
        this.value = undefined
        this.reason = undefined
        this.onFullfiledFun = [] // 存储异步
        this.onRejectedFun = [] // 存储异步

        executor(resolve, reject) // 立即执行

        function resolve(value) {
          if (_this.state === 'pending') {
            _this.value = value
            _this.onFullfiledFun.forEach((fn) => fn(value))
            _this.state = 'fulfilled'
          }
        }

        function reject(reason) {
          if (_this.state === 'pending') {
            _this.reason = reason
            _this.onRejectedFun.forEach((fn) => fn(reason))
            _this.state = 'rejected'
          }
        }
      }

      Promise.prototype.then = function (onFullfiled, onRejected) {
        var promise2 = new Promise((resolve, reject) => {
          // pending为等待态,异步还未完成
          if (this.state === 'pending') {
            if (typeof onFullfiled === 'function') {
              this.onFullfiledFun.push(onFullfiled)
            }
            if (typeof onRejected === 'function') {
              this.onRejectedFun.push(onRejected)
            }
          }
          if (this.state === 'fulfilled') {
            if (typeof onFullfiled === 'function') {
              onFullfiled(this.value)
            }
          }
          if (this.state === 'rejected') {
            if (typeof onRejected === 'function') {
              onRejected(this.reason)
            }
          }
        })
        return promise2
      }

      /**
       * 解析then返回值与新Promise对象
       * @param {Object} promise2 新的Promise对象
       * @param {*} x 上一个then的返回值
       * @param {Function} resolve promise2的resolve
       * @param {Function} reject promise2的reject
       */
      function resolvePromise(promise2, x, resolve, reject) {
        if (promise2 === x) {
          return new TypeError('Promise发生了循环引用')
        }
        if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
          // 可能是对象或者函数
          try {
            let then = x.then // 取出then方法引用

            // then是function,那么就执行promise
            if (typeof then === 'function') {
              let y = then.call(
                x,
                (y) => {
                  // 递归调用,传入y若是Promise对象,继续循环
                  resolvePromise(promise2, y, resolve, reject)
                },
                (r) => {
                  reject(r)
                },
              )
            } else {
              resolve(x)
            }
          } catch (e) {
            reject(e)
          }
        } else {
          // 否则是个普通值
          resolve(x)
        }
      }

 

你可能感兴趣的:(前端,promise)