登录
首页 >  文章 >  前端

实现PromiseA+规范的完整Promise库详解

时间:2026-03-15 23:41:42 132浏览 收藏

本文深入剖析了如何从零实现一个严格符合 Promise A+ 规范的完整 Promise 库,涵盖状态机设计(pending/fulfilled/rejected 三态不可逆)、executor 执行与错误捕获、异步回调队列管理、then 方法的链式返回与微任务调度、resolvePromise 对 thenable 和循环引用的精准处理,以及 resolve/reject/all/race 等核心静态方法的完备实现——不仅揭示了 Promise 背后精妙的状态流转与异步协调机制,更提供了一套可验证、可落地、经得起规范考验的手写实践方案,是深入理解 JavaScript 异步本质与现代前端底层原理的必读指南。

如何实现一个符合Promise A+规范的完整Promise库?

实现一个符合 Promise A+ 规范的 Promise 库,核心是理解并正确处理状态机、异步解析和 then 方法的链式调用。重点在于遵循规范中对 thenable 处理、状态不可逆变更、异步执行以及错误捕获的要求。

1. 定义基本状态与结构

Promise 有三种状态:pending、fulfilled、rejected,状态只能从 pending 变为 fulfilled 或 rejected,且一旦确定不可更改。

  • 使用常量表示状态:PENDING = 'pending', FULFILLED = 'fulfilled', REJECTED = 'rejected'
  • 每个 Promise 实例保存当前状态(this.state)、成功值(this.value)、失败原因(this.reason)
  • 维护 onFulfilled 和 onRejected 回调队列,用于处理异步 resolve/reject 的情况

构造函数接收一个 executor 函数,立即执行,并传入 resolve 和 reject 方法:

function MyPromise(executor) {
  this.state = PENDING;
  this.value = undefined;
  this.reason = undefined;
  this.onFulfilledCallbacks = [];
  this.onRejectedCallbacks = [];

  const resolve = (value) => {
    if (this.state === PENDING) {
      this.state = FULFILLED;
      this.value = value;
      this.onFulfilledCallbacks.forEach(fn => fn());
    }
  };

  const reject = (reason) => {
    if (this.state === PENDING) {
      this.state = REJECTED;
      this.reason = reason;
      this.onRejectedCallbacks.forEach(fn => fn());
    }
  };

  try {
    executor(resolve, reject);
  } catch (err) {
    reject(err);
  }
}

2. 实现 then 方法

then 是 Promise A+ 的核心,必须返回一个新的 Promise,以支持链式调用。它接收两个可选参数:onFulfilled 和 onRejected。

  • 根据当前状态决定如何处理回调:同步 resolved 就直接执行,异步则暂存到队列
  • 如果 onFulfilled/onRejected 是函数,必须异步执行(使用 setTimeout 模拟微任务)
  • 返回新 Promise,其状态由回调的返回值或异常决定

关键逻辑在处理返回值 x,需调用 resolvePromise 函数进行“解析”:

MyPromise.prototype.then = function(onFulfilled, onRejected) {
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
  onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };

  const promise2 = new MyPromise((resolve, reject) => {
    if (this.state === FULFILLED) {
      setTimeout(() => {
        try {
          const x = onFulfilled(this.value);
          resolvePromise(promise2, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      }, 0);
    }

    if (this.state === REJECTED) {
      setTimeout(() => {
        try {
          const x = onRejected(this.reason);
          resolvePromise(promise2, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      }, 0);
    }

    if (this.state === PENDING) {
      this.onFulfilledCallbacks.push(() => {
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      });

      this.onRejectedCallbacks.push(() => {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      });
    }
  });

  return promise2;
};

3. 实现 resolvePromise 辅助函数

这个函数处理 then 中回调返回的值 x,判断是否为 Promise 或 thenable 对象,决定如何 resolve 新的 promise2。

  • 如果 x 和 promise2 相同,抛出 TypeError(防止循环引用)
  • 如果 x 是对象或函数,尝试读取其 then 属性(注意可能抛错)
  • 如果 x 有 then 方法且是函数,则认为是 thenable,将其作为 Promise 处理
  • 否则将 x 作为普通值 resolve
function resolvePromise(promise2, x, resolve, reject) {
  if (x === promise2) {
    return reject(new TypeError('Chaining cycle detected'));
  }

  let called = false;
  if ((x !== null && typeof x === 'object') || typeof x === 'function') {
    try {
      const then = x.then;
      if (typeof then === 'function') {
        then.call(x, y => {
          if (called) return;
          called = true;
          resolvePromise(promise2, y, resolve, reject);
        }, r => {
          if (called) return;
          called = true;
          reject(r);
        });
      } else {
        resolve(x);
      }
    } catch (e) {
      if (called) return;
      called = true;
      reject(e);
    }
  } else {
    resolve(x);
  }
}

4. 补充常用方法

虽然 Promise A+ 只规定了 then,但完整的库通常包含以下静态方法:

  • MyPromise.resolve(value):返回一个 resolved 状态的 Promise
  • MyPromise.reject(reason):返回一个 rejected 状态的 Promise
  • MyPromise.all(promises):全部完成才 resolve,任意失败则 reject
  • MyPromise.race(promises):首个完成的 Promise 决定结果

例如 all 的实现:

MyPromise.all = function(promises) {
  return new MyPromise((resolve, reject) => {
    const results = [];
    let completedCount = 0;
    const total = promises.length;

    if (total === 0) {
      resolve(results);
      return;
    }

    for (let i = 0; i  {
        results[i] = value;
        completedCount++;
        if (completedCount === total) {
          resolve(results);
        }
      }, reject);
    }
  });
};

基本上就这些。只要严格按照 Promise A+ 规范处理状态流转、回调调度和链式解析,就能实现一个合规且可用的 Promise 库。测试时建议使用官方 promises-aplus-tests 工具验证兼容性。

理论要掌握,实操不能落!以上关于《实现PromiseA+规范的完整Promise库详解》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>