又是一个学习笔记

2021/4/18 18:57:11

本文主要是介绍又是一个学习笔记,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

promosie

异步链式调用 A+规范

/**
 * 异步链式调用 A+ 规范, 最简单的dome
 */
class PromiseA {
  constructor(init) {
    this.PromiseStatus = 'pending';
    let resolve = (val) => {
      if (this.resolveCallback) {
        this.PromiseStatus = 'fulfilled'
        this.resolveCallback(val)
      }
    }
    if (init) {
      init(resolve)
    }
  }

  then(onFulfill, onReject) {
    this.resolveCallback = onFulfill
    this.rejectCallback = onReject
    return this
  }
}

new PromiseA((resolve) => {
  console.log('resolve')
  setTimeout(() => {
    resolve("sss!? hello, from promise 1")
  }, 2000)
}).then((msg) => {
  console.log("ss", msg)
})

/**
 * 异步链式调用 A+ 规范
 * 处理的三个状态:pending, fulfilled, reject
 * pending 可以转化到 fulfilled 或 reject
 */
const isFunction = variable => typeof variable === 'function'

// 三个状态常量
const PENDING = 'PENDING'
const FULFILLDE = 'FULFILLED'
const REJECTED = 'REJECTED'

class MyPromise {
  constructor(handle) {
    if (!isFunction(handle)) {
      throw new Error('MyPromise must accept a function as a parameter')
    }
    // 添加状态
    this._status = PENDING
    this._value = undefined

    // 添加成功回调函数队列
    this._fulfilledQueues = []
    // 添加 失败回调函数队列
    this._rejectedQueues = []

    // 执行handle
    try {
      handle(this._resolve.bind(this), this._reject.bind(this))
    } catch (err) {
      this._reject(err)
    }
  }

  _resolve(val) {
    if (this._status !== PENDING) return

    // 依次执行成功队列中的函数,并清空队列
    // const run = () => {
    //   this._status = FULFILLDE
    //   this._value = val
    //   let cb
    //   while (cb = this._fulfilledQueues.shift()) {
    //     cb(val)
    //   }
    // }
    const run = () => {
      if (this._status !== PENDING) return
      // 依次执行成功队列中的函数,并清空队列
      const runFulfilled = (value) => {
        let cb
        while (cb = this._fulfilledQueues.shift()) {
          cb(value)
        }
      }
      // 依次执行失败队列中的函数,并清空
      const runRejected = (error) => {
        let cb;
        while (cb = this._rejectedQueues.shift()) {
          cb(error)
        }
      }

      if (val instanceof MyPromise) {
        val.then(value => {
          this._value = value
          this._status = FULFILLDE
          runFulfilled(value)
        }, err => {
          this._value = err
          this._status = REJECTED
          runRejected(err)
        })

      } else {
        this._value = val
        this._status = FULFILLDE
        runFulfilled(val)
      }
    }

    setTimeout(run, 0)
  }

  _reject(err) {
    if (this._status !== PENDING) return
    this._status = REJECTED
    this._value = err

    // 失败队列
    const run = () => {
      this._status = REJECTED
      this._value = err
      let cb
      while (cb = this._rejectedQueues.shift()) {
        cb(err)
      }

      setTimeout(run, 0)
    }
  }

  then(onFulfilled, onRejected) {
    const {
      _value,
      _status
    } = this
    // 返回一个新的Promise对象
    return new MyPromise((onFulfilledNext, onRejectedNext) => {
      // 封装一个成功时执行的函数
      let fulfilled = value => {
        try {
          if (!isFunction(onFulfilled)) {
            onFulfilledNext(value)
          } else {
            let res = onFulfilled(value)
            if (res instanceof MyPromise) {
              // 如果当前回调函数返回MyPromise对象,必须等待其状态改变后再执行下一个回调
              res.then(onFulfilledNext, onRejectedNext)
            } else {
              // 否则会将返回结果直接作为参数,传入下一个then的回调函数,并立即执行下一个then的回调函数
              onFulfilledNext(res)
            }
          }
        } catch (err) {
          onRejectedNext(err)
        }
      }
      // 封装一个失败时的执行函数
      let rejected = error => {
        try {
          if (!isFunction(onRejected)) {
            onRejectedNext(error)
          } else {
            let res = onRejected(error)
            if (res instanceof MyPromise) {
              // 如果当前回调函数返回MyPromise对象,必须等待其状态改变后再执行下一个回调
              res.then(onFulfilledNext, onRejectedNext)
            } else {
              onFulfilledNext(res)
            }
          }
        } catch (err) {
          // 出错
          onRejectedNext(err)
        }
      }
      switch (_status) {
        // 当状态位pending时,将then方法回调函数加入执行队列等待执行
        case PENDING:
          this._fulfilledQueues.push(fulfilled)
          this._rejectedQueues.push(rejected)
          break
  
          // 当状态变更立即执行对应的回调函数
        case FULFILLDE:
          fulfilled(_value)
          break
  
        case REJECTED:
          rejected(_value)
          break
      }
    })
  }
  catch (onRejected) {
    return this.then(undefined, onRejected)
  }

  // 静态resolve方法
  static resolve(value) {
    // 如果参数好似MyPromise实例,直接返回这个实例
    if (value instanceof MyPromise) {
      return value
    }

    return new MyPromise(resolve => resolve(value))
  }

  // 静态reject方法
  static reject(value) {
    return new MyPromise((resolve, reject) => reject(value))
  }

  // 静态方法all
  static all(list) {
    return new MyPromise((resolve, reject) => {
      // 返回值集合
      let values = []
      let count = 0
      for (let [i, p] of list.entries()) {
        // 数组参数如果不是MyPromise实例,先调用MyPromise.resolve
        this.resolve(p).then(res => {
          values[i] = res
          count++

          // 所有状态都变成fulfilled的时候返回的MyPromise状态就变成fufilled
          if (count === list.length) resolve(values)
        }, err => {
          // 有一个被rejected是返回MyPromise状态就变成rejected
          reject(err)
        })
      }
    })
  }
  // 静态 race 方法
  static race (list) {
    return new MyPromise((resolve, reject) => {
      for (let p of list) {
        // 只要有一个实例率先改变状态,新的MyPromise的状态就跟着改变
        this.resolve(p).then(res => {
          resolve(res)
        }, err => {
          reject(err)
        })
      }
    })
  }
  // finally 方法
  finally (cb) {
    return this.then(
      value => MyPromise.resolve(cb()).then(() => value),
      reason => MyPromise.resolve(cb()).then(() => { throw reason })
    )
  }

}

console.log('00000---->>>>')

let promise1 = new MyPromise((resolve, reject) => {
  resolve('zhg shi cengg')
  setTimeout(() => {
    console.log('2222')
  }, 2000)
})

promise1.then((res) => {
  console.log('then', res)
})

promisify

/**
 * promisify就是“promise化”
 * 将一个不是promise的方法变成promise.
 * 举个

	


这篇关于又是一个学习笔记的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程