自己实现一个Promise

promise是前端解决异步的一个重要的东西。其主要使用如下:

    const p1 = new Promise((resolve, reject) => {
      // 此处走then方法
      resolve(111)
      // 此处走catch方法
      // reject(222)
    })
    p1.then((res) => {
      console.log(res);
    }).catch(err => {
      console.log(err);
    })

请自己实现一个Promise方法,可以满足以上的功能。

    class MyPromise {
      constructor(executor) {
        executor(this.resolve.bind(this), this.reject.bind(this))
      }
      state = 'pending'
      // 成功的值
      value = null
      // 失败的值
      reason = null
      // 当走到then/catch方法的时候,如果状态没变化,就暂时先声明一个变量去缓存方法,等到状态变化的时候再去执行
      onFulfilledCallbackList = []
      onRejectedCallbackList = []

      resolve(value) {
        if (this.state !== 'pending') return;
        this.state = 'fulfilled'
        this.value = value
        this.onFulfilledCallbackList.forEach(callback => callback(value))
        this.onFulfilledCallbackList = []
      }
      reject(reason) {
        if (this.state !== 'pending') return;
        this.state = 'rejected'
        this.reason = reason
        this.onRejectedCallbackList.forEach(callback => callback(reason))
        this.onRejectedCallbackList = []
      }
      then(onFulFilled, onRejected) {
        return new MyPromise((res, rej) => {
          if (this.state === 'fulfilled') {
            res(onFulFilled(this.value))
          };
          if (this.state === 'rejected') {
            rej(onRejected(this.reason))
          };
          if (this.state === 'pending') {
            this.onFulfilledCallbackList.push(onFulFilled)
            this.onRejectedCallbackList.push(onRejected)
          };

        })
      }
    }
    const myP1 = new MyPromise((resolve, reject) => {
      console.log('立即执行');
      resolve(111)
      // setTimeout(() => {
      //   resolve(111)
      // }, 3000)
    }).then(res => {
      console.log('成功了', res);
    }, err => {
      console.log('失败了', err);
    }).then(res => {
      console.log('链式调用then方法', res);
    })

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值