前端系统学习1. Promise

Promise

  • state
  • then

state有三种,pending fulfilled rejected

then有两个回调参数,onFulfilled onRejected

Promise状态的扭转时会从 pending 变为其他两种状态,此时会调用 then 传入的两个回调分别处理这两种状态

同一个promise可以调用多个then,状态扭转时,按照then调用的顺序执行他们传入的回调。

当then接受的两个参数不是函数时,then会给出一个默认函数用来透传参数

promise 初始化时传入的回调时立即执行的,而 then 的两个回调是通过 queueMicrotask 放入微任务队列执行的

resolvePromise 做的特殊处理:

  1. 如果 promise2 和 x 相等,那么 reject TypeError
  2. 如果 x 是一个 promsie
    如果x是pending态,那么promise必须要在pending,直到 x 变成 fulfilled or rejected.
    如果 x 被 fulfilled, fulfill promise with the same value.
    如果 x 被 rejected, reject promise with the same reason.
  3. 如果 x 是一个 object 或者 是一个 function
    let then = x.then.
    如果 x.then 这步出错,那么 reject promise with e as the reason.
    如果 then 是一个函数,then.call(x, resolvePromiseFn, rejectPromise)
    resolvePromiseFn 的 入参是 y, 执行 resolvePromise(promise2, y, resolve, reject);
    rejectPromise 的 入参是 r, reject promise with r.
    如果 resolvePromise 和 rejectPromise 都调用了,那么第一个调用优先,后面的调用忽略。
    如果调用then抛出异常e
    如果 resolvePromise 或 rejectPromise 已经被调用,那么忽略
    则,reject promise with e as the reason
    如果 then 不是一个function. fulfill promise with x.

Promise.all 公开课

自己代码实现

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

function isFunction (f) {
  return typeof f === 'function'
}

class MPromise {
  ONFULFILLED_CALLBACKS = []
  ONREJECTED_CALLBACKS = []
  _status = PENDING

  constructor(fn) {
    this.status = PENDING
    this.value = null
    this.reason = null

    // 立即执行fn
    try {
      fn(this.resolve.bind(this), this.reject.bind(this))
    } catch(e) {
      this.reject(e)
    }
  }

  get status() {
    return this._status
  }

  set status(s) {
    this._status = s
    switch(s) {
      case FULFILLED: {
        this.ONFULFILLED_CALLBACKS.forEach(item => {
          item(this.value)
        })
        break
      }
      case REJECTED: {
        this.ONREJECTED_CALLBACKS.forEach(item => {
          item(this.reason)
        })
        break
      }
    }
  }

  resolve(value) {
    if (this.status === PENDING) {
      this.value = value
      this.status = FULFILLED
    }
  }

  reject(reason) {
    if (this.status === PENDING) {
      this.reason = reason
      this.status = REJECTED
    }
  }

  then(onFulfilled, onRejected) {
    const realOnFulfilled = isFunction(onFulfilled) ? onFulfilled : v => v
    const realOnRejected = isFunction(onRejected) ? onRejected : reason => {
      throw reason
    }

    const promise2 = new MPromise((resolve, reject) => {
      const onFulFillMicroTask = (value) => {
        queueMicrotask(() => {
          try {
            const x = realOnFulfilled(value)
            this.resolvePromsie(promise2, x, resolve, reject)
          } catch(e) {
            reject(e)
          }
        })
      }
      const onRejectMicroTask = (reason) => {
        queueMicrotask(() => {
          try {
            const x = realOnRejected(reason)
            this.resolvePromsie(promise2, x, resolve, reject)
          } catch(e) {
            reject(e)
          }
        })
      }

      // 如果then在调用的时候promise的状态已经发生了变化,需要手动调用回调
      switch(this.status) {
        case FULFILLED: {
          onFulFillMicroTask(this.value)
          break
        }
        case REJECTED: {
          onRejectMicroTask(this.reason)
          break
        }
        case PENDING: {
          this.ONFULFILLED_CALLBACKS.push(onFulFillMicroTask)
          this.ONREJECTED_CALLBACKS.push(onRejectMicroTask)
        }
      }
    })

    return promise2
  }

  catch(onRejected) {
    return this.then(null, onRejected)
  }

  resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
      return reject(new TypeError('The promise and the return value are the same'))
    } else if (x instanceof MPromise) {
      // 这里我并没有用queueMicrotask
      x.then(value => {
        this.resolvePromise(promise2, value, resolve, reject)
      }, reject)
    } else if (typeof x === 'object' || isFunction(x)) {
      if (x === null) return resolve(x)

      let then = null
      try {
        then = x.then
      } catch(e) {
        return reject(e)
      }

      if (isFunction(then)) {
        // 保证对该 promise like 对象的then函数只接受其一次状态扭转调用,
        // 因为该 promise like 对象不可信,所以此处需要严格限制。
        // 上面判断x instance MPromise保证x整个对象是我们自己控制的,所以无需判断
        let called = false
        try {
          then.call(
            x,
            (value) => {
              if (called) return
              called = true
              this.resolvePromise(promise2, value, resolve, reject)
            },
            (reason) => {
              if (called) return
              called = true
              reject(reason)
            }
          )
        } catch(e) {
          if (called) return
          // 只有在调用onFulfill onReject扭转状态时才需要called置为true,普通抛错并不代表状态完成扭转,所以还可以调用扭转回调
          return reject(e)
        }
      } else {
        resolve(x)
      }
    } else {
      resolve(x)
    }
  }

  static resolve(value) {
    if (value instanceof MPromise) return value

    return new MPromise((resolve) => {
      resolve(value)
    })
  }

  static reject(reason) {
    return new MPromise((resolve, reject) => {
      reject(reason)
    })
  }

  static race(promiseList) {
    return new MPromise((resolve, reject) => {
      if (!promiseList || !promiseList.length) return resolve()

      promiseList.forEach(promise => {
        MPromise.resolve(promise).then(
          (value) => {
            resolve(value)
          },
          reason => {
            reject(reason)
          }
        )
      })
    })
  }
}

const promise = new MPromise((resolve, reject) => {
  resolve(123)
})

const promise2 = promise.then((value) => {

}, (reason) => {

})

// const test = new MPromise((resolve, reject) => {
//   setTimeout(() => {
//       reject(111);
//   }, 1000);
// }).then((value) => {
//   console.log('then');
// }).catch((reason) => {
//   console.log('catch');
// })

MPromise.race([
  // 1,
  // MPromise.resolve(2),
  new MPromise((resolve, reject) => {
    setTimeout(() => {
      resolve(3)
    }, 1000);
  }),
  new MPromise((resolve, reject) => {
    setTimeout(() => {
      reject(4)
    }, 1100);
  }),
]).then(
  (value) => {
    console.log('resolve', value)
  },
  (reason) => {
    console.log('reject', reason)
  }
)

// 对于代码中有的实现, 有的同学可能会有疑问, 这里为什么会有异常, 为什么一定要这么写.
// 大家可以去看一下promise aplus的测试用例, 里面列举了各种奇奇怪怪的异常情况 https://github.com/promises-aplus/promises-tests/blob/master/lib/tests.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容