手写promise

原本promise是这样调用的

	    let p = new Promise((resolve, inject) => {
          setTimeout(() => {
            resolve(111)
          })
        })
        p.then((res) => {
          console.log(res)
        })

手写自定义promise

class Mypromise { //定义一个类
          constructor(fncallback) { //传入回调函数进行直接调用
            this.state = 'padding' //三个状态padding、resolve、jnject
            this.value = '' //成功状态下的正确的值
            this.err = '' //错误状态下的错误信息
            fncallback(this.success.bind(this), this.fail.bind(this)) //及时调用回调绑定函数中的this指向(此时this指向的是undefind)
          }
          success(value) { //当成功状态时的调用
            this.value = value //当前的value的值
            this.state = 'resolve' //状态为resolve
            this.then(this.cuccessm, this.file) //当异步操作完成时进行调用
          }
          fail(err) {
            this.err = err
            this.state = 'inject'
            this.then(this.cuccessm, this.file)
          }
          then(cuccessm, file = () => {}) { //首先调用的是then方法,此时状态还为padding把传过来的成功的回调以及错误的回调挂载到this上
            if (this.state == 'resolve') {
              cuccessm(this.value)
            } else if (this.state == 'inject') {
              fail(this.err)
            } else {
              this.cuccessm = cuccessm
              this.fail = fail
            }
            return this
          }
        }

调用

new Mypromise((resolve, inject) => {
          setTimeout(() => {
            resolve(222)
          })
        }).then((res) => {
          console.log(res)
        })
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值