美文网首页
原生 ES6 实现 Promise

原生 ES6 实现 Promise

作者: 三十文 | 来源:发表于2018-11-20 19:58 被阅读7次
    const PENDING = Symbol('pending')
    const FULLFILLED = Symbol('fullfilled')
    const REJECTED = Symbol('rejected')
    
    class Promise {
      constructor (fn) {
        this.status = PENDING
        this.value = undefined
        this.resolveFunc = () => {
        }
        this.rejectFunc = () => {
    
        }
    
        fn.call(this, this.resolve.bind(this), this.reject.bind(this))
      }
    
      resolve (value) {
        if (this.status == PENDING) {
          this.status = FULLFILLED
          this.value = value
          this.resolveFunc(value)
        }
      }
    
      reject (value) {
        if (this.status == PENDING) {
          this.status = REJECTED
          this.value = value
          this.rejectFunc(value)
        }
      }
    
      then (resolveFunc, rejectFunc) {
        return new Promise((resolve_next, reject_next) => {
          const resolveFuncWrap = () => {
            try {
              let result = resolveFunc(this.value)
              if (result && typeof result.then == 'function') {
                result.then(resolve_next, reject_next)
              } else {
                resolve_next(result)
              }
            } catch (e) {
              reject_next(e)
            }
          }
    
          const rejectFuncWrap = () => {
            let result = rejectFunc(this.value)
            reject_next(result)
          }
    
          this.resolveFunc = resolveFuncWrap
          this.rejectFunc = rejectFuncWrap
        })
      }
    
      catch (errCallback) {
        this.rejectFunc = errCallback
      }
    }
    
    
    
    let hello = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('hello')
        }, 1000)
      })
    }
    
    hello().then(res1 => {
      console.log('res1: ', res1)
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('world')
        })
      })
    }).then(res2 => {
      console.log('res2:', res2)
      // 测试出 error 情况
      console.log('error:', hello.i.b)
    }).catch(err => {
      console.log('error: ', err)
    })
    

    相关文章

      网友评论

          本文标题:原生 ES6 实现 Promise

          本文链接:https://www.haomeiwen.com/subject/zatfqqtx.html