深度解析Promise的核心功能并手写实现

167 篇文章 3 订阅

码字不易,有帮助的同学希望能关注一下我的微信公众号:Code程序人生,感谢!代码自用自取。

在这里插入图片描述

Promise作为前端目前必不可少的内容,目前对于前端工程师的考察已经不满足于对于Promise的简单使用,中大公司的要求是知道原理,能手写实现

Promise最基本的特性,要提供三个方法,resolve、reject、then。

class Promise {
  static PENDING = "PENDING";
  static FULFILLED = "FULFILLED";
  static REJECTED = "REJECTED";
  constructor(func) {
    this.status = Promise.PENDING;
    this.result = null;
    this.resolveCallBacks = [];
    this.rejectCallBacks = [];
    // 原生promise中, 如果在构造函数里throw new Error, .then的时候会走reject
    // 并且会打印出throw的内容
    try {
      func(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
      this.reject(error);
    }
  }
  resolve(result) {
    setTimeout(() => {
      if (this.status === Promise.PENDING) {
        this.status = Promise.FULFILLED;
        this.result = result;
        this.resolveCallBacks.forEach((callback) => {
          callback(result);
        });
      }
    });
  }
  reject(result) {
    setTimeout(() => {
      if (this.status === Promise.PENDING) {
        this.status = Promise.REJECTED;
        this.result = result;
        this.rejectCallBacks.forEach((callback) => {
          callback(result);
        });
      }
    });
  }
  then(onFULFILLED, onREJECTED) {
    return new Promise((resolve, reject) => {
      onFULFILLED = typeof onFULFILLED === "function" ? onFULFILLED : () => {};
      onREJECTED = typeof onREJECTED === "function" ? onREJECTED : () => {};
      if (this.status === Promise.PENDING) {
        this.resolveCallBacks.push(onFULFILLED);
        this.rejectCallBacks.push(onREJECTED);
      }
      if (this.status === Promise.FULFILLED) {
        setTimeout(() => {
          onFULFILLED(this.result);
        });
      }
      if (this.status === Promise.REJECTED) {
        setTimeout(() => {
          onREJECTED(this.result);
        });
      }
    });
  }
}

简单说几个需要注意的点:

  • Promise中有三种状态,等待中PENDING,成功FULFILLED,失败REJECTED
  • 构造函数中要将状态置为等待中,try catch的作用是在Promise构造函数中如何代码出现异常,会走reject的,需要用try catch来处理一下
  • 两个更改方法的方法,resolve、reject,最核心的功能就是通过setTimeout来实现异步执行,执行的代码就是更改状态,保存传入的值,将其放入自己的待处理队列中
  • then方法是Promise最核心的功能,在面试的时候如何对于Promise的考察浅一些,会问你为什么Promise可以实现链式调用。原理就是then方法中整体返回了一个新的Promise实例,所以才可以一直.then。对于then方法的参数的判断是因为,如果Promise的then方法,你传入的参数不是函数,它会给你转成一个空函数,这种操作需要源码处理,就是我这样的操作。然后就是判断当前的状态,等待中说明还没有执行resolve或者reject方法,就把当前的成功和失败回调放入对应的待处理队列里。如果是成功或失败,就去异步执行成功或失败的回调。

Promise的考察从初级前端到高级前端都会有,大家要深刻理解Promise的意义,才能够手写源码实现

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CreatorRay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值