返回

手把手带你从0实现Promise(二)

前端

1. Promise基础知识

Promise是JavaScript中用于处理异步操作的强大工具,它允许你在异步操作完成后执行相应的操作。Promise有三种状态:pending(等待)、fulfilled(已完成)和rejected(已拒绝)。

实现Promise类,首先需要定义一个构造函数,该函数接受一个executor函数作为参数。executor函数有两个参数:resolve和reject,它们用于改变Promise的状态。

class Promise {
  constructor(executor) {
    this.state = 'pending';
    this.value = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    // 立即执行executor函数
    executor(resolve, reject);
  }

2. 改变this指向

在JavaScript中,this指向调用函数的对象。在Promise类中,我们需要改变this指向,以便在resolve和reject函数中访问Promise实例。

可以使用call、apply和bind来改变this指向。

class Promise {
  // ...

  // 使用call改变this指向
  then(onFulfilled, onRejected) {
    return this.then(onFulfilled.bind(this), onRejected.bind(this));
  }

3. 事件循环

事件循环是JavaScript的运行机制,它负责执行代码和处理事件。

在事件循环中,有一个专门用于处理异步操作的队列,当异步操作完成时,会将结果放入队列中。

Promise通过注册回调函数来监听状态的变化,当状态发生变化时,会将对应的回调函数放入队列中,等待事件循环执行。

class Promise {
  // ...

  // 注册回调函数
  then(onFulfilled, onRejected) {
    if (this.state === 'fulfilled') {
      // 如果状态已完成,立即执行onFulfilled回调函数
      onFulfilled(this.value);
    } else if (this.state === 'rejected') {
      // 如果状态已拒绝,立即执行onRejected回调函数
      onRejected(this.reason);
    } else {
      // 如果状态仍等待,将回调函数放入队列中
      this.onFulfilledCallbacks.push(onFulfilled);
      this.onRejectedCallbacks.push(onRejected);
    }

4. 实现更灵活的代码

可以使用call、apply和bind来实现更灵活的代码。

class Promise {
  // ...

  // 使用call执行onFulfilled回调函数
  then(onFulfilled, onRejected) {
    return this.then(onFulfilled.bind(this), onRejected.bind(this));
  }

  // 使用apply执行onFulfilled回调函数
  then(onFulfilled, onRejected) {
    return this.then((value) => onFulfilled.apply(this, [value]),
    (reason) => onRejected.apply(this, [reason]));
  }

  // 使用bind返回一个新的Promise实例
  then(onFulfilled, onRejected) {
    return this.then(onFulfilled.bind(this), onRejected.bind(this))
    .then((value) => value, (reason) => reason);
  }

通过实现一个基本的Promise类,可以深入理解Promise的基础知识,掌握Class类的用法,以及如何在JavaScript中改变this指向。通过Event Loop来理解Promise的工作原理,并借助call、apply和bind来实现更灵活的代码。希望本文能够帮助你对Promise有一个更加深入的理解和掌握。