返回

用ES6实现一个简单易懂的Promise(遵循Promise/A+ 规范并附详解注释)

前端

用ES6实现一个简单易懂的Promise(遵循Promise/A+ 规范并附详解注释)

ES6新增了Promise这个特性,它可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操作更加容易。

Promise/A+规范

Promise/A+规范是一套规范,它定义了Promise对象的行为。所有遵循Promise/A+规范的Promise对象都具有相同的基本行为。

实现一个简单的Promise

class Promise {
  constructor(executor) {
    // Promise的状态,有三种状态:pending、fulfilled、rejected
    this.state = 'pending';

    // Promise的结果值
    this.value = undefined;

    // Promise的拒绝原因
    this.reason = undefined;

    // 存储等待onFulfilled和onRejected回调函数的数组
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    // 执行器函数,用于初始化Promise的状态和结果
    try {
      executor(this.resolve.bind(this), this.reject.bind(this));
    } catch (error) {
      this.reject(error);
    }
  }

  // 使Promise的状态变为fulfilled,并执行onFulfilled回调函数
  resolve(value) {
    if (this.state !== 'pending') {
      return;
    }

    this.state = 'fulfilled';
    this.value = value;

    this.onFulfilledCallbacks.forEach(callback => {
      callback(value);
    });
  }

  // 使Promise的状态变为rejected,并执行onRejected回调函数
  reject(reason) {
    if (this.state !== 'pending') {
      return;
    }

    this.state = 'rejected';
    this.reason = reason;

    this.onRejectedCallbacks.forEach(callback => {
      callback(reason);
    });
  }

  // then方法,用于添加onFulfilled和onRejected回调函数
  then(onFulfilled, onRejected) {
    return new Promise((resolve, reject) => {
      // 如果Promise的状态是fulfilled,则立即执行onFulfilled回调函数
      if (this.state === 'fulfilled') {
        onFulfilled(this.value);
      }

      // 如果Promise的状态是rejected,则立即执行onRejected回调函数
      else if (this.state === 'rejected') {
        onRejected(this.reason);
      }

      // 如果Promise的状态是pending,则将onFulfilled和onRejected回调函数添加到相应的数组中
      else {
        this.onFulfilledCallbacks.push(() => {
          onFulfilled(this.value);
        });

        this.onRejectedCallbacks.push(() => {
          onRejected(this.reason);
        });
      }
    });
  }
}

使用Promise

// 创建一个Promise对象
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Hello, world!');
  }, 1000);
});

// 使用then方法添加onFulfilled和onRejected回调函数
promise.then(
  (value) => {
    console.log(value); // 输出:Hello, world!
  },
  (reason) => {
    console.log(reason); // 不会输出任何内容
  }
);

总结

Promise是一种非常有用的工具,它可以使异步编程更加容易。本文介绍了如何用ES6实现一个简单的Promise,并遵循Promise/A+规范。