首页 > web前端 > js教程 > 正文

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

幻影之瞳
发布: 2025-10-02 18:06:02
原创
145人浏览过
实现一个符合 Promise A+ 规范的 Promise 库,需定义 PENDING、FULFILLED、REJECTED 三种状态,构造函数执行 executor 并传入 resolve 和 reject 方法,通过 onFulfilledCallbacks 和 onRejectedCallbacks 存储异步回调;then 方法返回新 Promise,根据当前状态异步执行 onFulfilled 或 onRejected,并调用 resolvePromise 解析返回值 x;resolvePromise 函数处理 x 为 promise 或 thenable 的情况,防止循环引用并确保状态只改变一次;最后补充 MyPromise.resolve、reject、all、race 等静态方法以完善功能。整个实现需严格遵循规范对状态机、异步执行、错误捕获和链式调用的要求。

如何实现一个符合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 函数进行“解析”:

库宝AI
库宝AI

库宝AI是一款功能多样的智能伙伴助手,涵盖AI写作辅助、智能设计、图像生成、智能对话等多个方面。

库宝AI109
查看详情 库宝AI
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 < total; i++) {
      MyPromise.resolve(promises[i]).then(value => {
        results[i] = value;
        completedCount++;
        if (completedCount === total) {
          resolve(results);
        }
      }, reject);
    }
  });
};
登录后复制

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

以上就是如何实现一个符合Promise A+规范的完整Promise库?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号