返回

逐行注释 Promise/A+ 规范,实现基础中的基础,带你站在面试者的角度理解 Promise

前端

Promise/A+ 规范对 Promise 对象的行为和用法做了详细的规定。Promise 对象是一个表示异步操作的占位符,它可以处于三种状态:pending(等待)、fulfilled(已完成)和 rejected(已拒绝)。当异步操作完成时,Promise 对象的状态会从 pending 变为 fulfilled 或 rejected,并触发相应的回调函数。

Promise/A+ 规范规定了 Promise 对象必须具备以下方法:

  • then(onFulfilled, onRejected):用于为 Promise 对象添加回调函数。onFulfilled 回调函数在 Promise 对象的状态变为 fulfilled 时被调用,onRejected 回调函数在 Promise 对象的状态变为 rejected 时被调用。
  • catch(onRejected):用于为 Promise 对象添加一个只处理 rejected 状态的回调函数。
  • finally(onFinally):用于为 Promise 对象添加一个无论 fulfilled 或 rejected 都会被调用的回调函数。

以下是如何按照 Promise/A+ 规范逐行注释并实现一个 Promise 对象的代码:

// Promise 构造函数
function Promise(executor) {
  // Promise 的状态
  this.state = 'pending';

  // Promise 的值或错误信息
  this.value = undefined;

  // Promise 的回调函数队列
  this.onFulfilledCallbacks = [];
  this.onRejectedCallbacks = [];

  // 执行器函数
  try {
    executor(resolve, reject);
  } catch (e) {
    reject(e);
  }

  // 解析函数
  function resolve(value) {
    if (this.state !== 'pending') {
      return;
    }

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

    // 执行回调函数
    this.onFulfilledCallbacks.forEach(callback => callback(this.value));
  }

  // 拒绝函数
  function reject(reason) {
    if (this.state !== 'pending') {
      return;
    }

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

    // 执行回调函数
    this.onRejectedCallbacks.forEach(callback => callback(this.value));
  }
}

// then 方法
Promise.prototype.then = function(onFulfilled, onRejected) {
  // 处理参数
  if (typeof onFulfilled !== 'function') {
    onFulfilled = value => value;
  }
  if (typeof onRejected !== 'function') {
    onRejected = reason => { throw reason; };
  }

  // 返回一个新的 Promise 对象
  return new Promise((resolve, reject) => {
    // 添加回调函数到队列
    this.onFulfilledCallbacks.push(value => {
      try {
        // 执行回调函数
        const result = onFulfilled(value);

        // 根据结果决定新的 Promise 对象的状态
        if (result instanceof Promise) {
          result.then(resolve, reject);
        } else {
          resolve(result);
        }
      } catch (e) {
        reject(e);
      }
    });

    this.onRejectedCallbacks.push(reason => {
      try {
        // 执行回调函数
        const result = onRejected(reason);

        // 根据结果决定新的 Promise 对象的状态
        if (result instanceof Promise) {
          result.then(resolve, reject);
        } else {
          resolve(result);
        }
      } catch (e) {
        reject(e);
      }
    });
  });
};

// catch 方法
Promise.prototype.catch = function(onRejected) {
  return this.then(undefined, onRejected);
};

// finally 方法
Promise.prototype.finally = function(onFinally) {
  return this.then(value => {
    onFinally();
    return value;
  }, reason => {
    onFinally();
    throw reason;
  });
};

以上是如何按照 Promise/A+ 规范逐行注释并实现一个 Promise 对象的代码。通过阅读本文,读者可以深入理解 Promise 的工作原理,并掌握 Promise 的正确使用方法。此外,本文还提供了一些面试技巧,帮助读者在面试中应对有关 Promise 的问题。