Promise

37 阅读1分钟
class myPromise() {  constructor(fn) {    this.state = 'pending'    this.result = undefined this.cbList = []    const resolve = (res) => {      if (this.state !== 'pending') return this.state = 'fullfilled'      this.result = res setTimeout(() => {        this.cbList.forEach(cb => cb.onResolved(res))      })    }    const reject = (err) => {      if (this.state !== 'pending') return this.state = 'rejected'      this.result = err setTimeout(() => {        this.cbList.forEach(cb => cb.onRejected(err))      })    }    try {      fn(resolve, reject)    } catch (err) {      reject(err)    }  }  then(onResolved, onRejected) {    if (typeof onResolved !== 'function') {      onResolved = (val) => val    }    if (typeof onRejected !== 'function') {      onRejected = (err) => {        throw (err)      }    }    return new myPromise((rs, rj) => {      const handleCb = (callback) => {        try {          const res = callback(this.result) if (res instanceof myPromise) {            res.then(val => rs(val), err => rj(err))          } else {            rs(res)          }        } catch (e) {          rj(e)        }      }      if (this.state === 'fullfilled') {        setTimeout(() => {          handleCb(onResolved)        })      }      if (this.state === 'rejected') {        setTimeout(() => {          handleCb(onRejected)        })      }      if (this.state === 'pending') {        this.cbList.push({          onResolved: () => {            handleCb(onResolved)          },          onRejected: () => {            handleCb(onRejected)          },        })      }    })  } catch (fn) {    return this.then(undefined, fn)  }  static resolve(val) {    return new myPromise((rs, rj) => {      if (val instanceof myPromise) {        val.then(value => rs(value), err => rj(err))      } else {        rs(val)      }    })  }  static reject(err) {    return new myPromise((rs, rj) => {      rj(err)    })  }  static all(promiseList) {    const l = promiseList.length    const resList = []    return new myPromise((rs, rj) => {      promiseList.forEach((p, i) => {        p.then(res => {          resList.push(res) if (resList.length === l) {            rs(resList)          }        }).catch(err => {          rj(err)        })      })    })  }  static race(promiseList) {    return new myPromise((rs, rj) => {      promiseList.forEach((p, i) => {        p.then(res => {          rs(res)        }).catch(err => {          rj(err)        })      })    })  }}




function Parent() {}function Child(...args) {  Parent.apply(this, args)}function Fn() {}Fn.prototype = Parent.prototypeChild.prototype = new Fn()function myNew(Fn, ...args)() {  const obj = {}  obj.prototype = Object.create(Fn.prototype) Fn.apply(obj, args) return obj}