返回

探秘ES6 Promise核心机制,手把手教你实现Promise

前端

  1. 什么是Promise?

在JavaScript中,Promise是一个对象,它代表一个异步操作的最终完成或失败。我们可以使用Promise来跟踪异步操作的执行,并根据其结果做出相应的处理。

2. Promise的基本用法

Promise的基本用法如下:

// 创建一个Promise对象
const promise = new Promise((resolve, reject) => {
  // 在异步操作成功时调用resolve()
  resolve('成功结果');

  // 在异步操作失败时调用reject()
  reject('失败原因');
});

// 使用then()方法处理Promise的结果
promise.then(result => {
  // 如果Promise成功,则执行此回调函数
  console.log(`成功结果:${result}`);
}, error => {
  // 如果Promise失败,则执行此回调函数
  console.log(`失败原因:${error}`);
});

3. Promise的实现

我们可以使用以下步骤实现一个简化版的Promise:

  1. 定义一个Promise类
class Promise {
  constructor(executor) {
    this.state = 'pending'; // 初始状态为pending
    this.result = undefined; // 结果
    this.callbacks = []; // 回调函数队列

    // 执行executor函数
    executor(this.resolve.bind(this), this.reject.bind(this));
  }

  resolve(result) {
    if (this.state !== 'pending') return;

    this.state = 'fulfilled'; // 状态变为fulfilled
    this.result = result; // 保存结果

    // 执行回调函数队列
    this.callbacks.forEach(callback => callback.onFulfilled(result));
  }

  reject(error) {
    if (this.state !== 'pending') return;

    this.state = 'rejected'; // 状态变为rejected
    this.result = error; // 保存结果

    // 执行回调函数队列
    this.callbacks.forEach(callback => callback.onRejected(error));
  }

  then(onFulfilled, onRejected) {
    return new Promise((resolve, reject) => {
      this.callbacks.push({
        onFulfilled: result => {
          // 如果onFulfilled是函数,则执行它,否则直接使用结果
          const value = typeof onFulfilled === 'function' ? onFulfilled(result) : result;

          // 将结果传递给下一个Promise
          resolve(value);
        },
        onRejected: error => {
          // 如果onRejected是函数,则执行它,否则直接使用错误
          const value = typeof onRejected === 'function' ? onRejected(error) : error;

          // 将错误传递给下一个Promise
          reject(value);
        }
      });
    });
  }
}
  1. 使用Promise
// 创建一个Promise对象
const promise = new Promise((resolve, reject) => {
  // 模拟异步操作
  setTimeout(() => {
    if (Math.random() > 0.5) {
      resolve('成功结果');
    } else {
      reject('失败原因');
    }
  }, 1000);
});

// 使用then()方法处理Promise的结果
promise.then(result => {
  console.log(`成功结果:${result}`);
}, error => {
  console.log(`失败原因:${error}`);
});

4. 结语

通过本文,我们对ES6 Promise有了更深入的了解,并手把手实现了一个简化版的Promise。希望本文能够帮助你更好地掌握ES6 Promise,并能够在实际项目中使用它来编写更健壮、更易读的代码。