登录
首页 >  文章 >  前端

手写Promise源码,深入解析Promises/A+规范

时间:2025-12-09 15:44:30 315浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

文章不知道大家是否熟悉?今天我将给大家介绍《手写Promise实现,深入理解Promises/A+规范》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

答案:文章实现了一个符合Promises/A+规范的简易Promise,包含三种状态(pending、fulfilled、rejected)、构造函数、then方法链式调用、resolvePromise解析逻辑及静态resolve/reject方法,通过queueMicrotask处理异步回调,支持Promise链式传递与错误捕获。

手写一个符合Promises/A+规范的Promise_javascript进阶

实现一个符合 Promises/A+ 规范的 Promise 并不是一件简单的事,但通过一步步拆解核心逻辑,我们可以手写一个基本符合规范的简易版本。下面是一个简化但关键流程正确的 Promise 实现,帮助你深入理解其工作机制。

Promise 的三种状态

根据 Promises/A+ 规范,Promise 有三种状态:

  • pending:初始状态,未 fulfilled 或 rejected
  • fulfilled:成功状态,不可逆
  • rejected:失败状态,不可逆

状态一旦从 pending 变为 fulfilled 或 rejected,就不能再改变。

Promise 构造函数实现

我们从构造函数开始,接收一个执行器函数(executor),并初始化状态和值。

function MyPromise(executor) {
  this.status = 'pending';
  this.value = undefined;
  this.reason = undefined;

  // 存储 then 注册的成功和失败回调
  this.onFulfilledCallbacks = [];
  this.onRejectedCallbacks = [];

  const resolve = (value) => {
    if (this.status === 'pending') {
      this.status = 'fulfilled';
      this.value = value;
      // 执行所有成功的回调
      this.onFulfilledCallbacks.forEach(fn => fn());
    }
  };

  const reject = (reason) => {
    if (this.status === 'pending') {
      this.status = 'rejected';
      this.reason = reason;
      // 执行所有失败的回调
      this.onRejectedCallbacks.forEach(fn => fn());
    }
  };

  try {
    executor(resolve, reject);
  } catch (error) {
    reject(error); // 如果执行器出错,直接 reject
  }
}

then 方法的实现

then 方法是 Promise 的核心,用于注册成功和失败的回调,并返回一个新的 Promise,支持链式调用。

MyPromise.prototype.then = function(onFulfilled, onRejected) {
  // 处理回调可选的情况
  onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
  onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };

  // 返回一个新的 Promise
  const promise2 = new MyPromise((resolve, reject) => {
    if (this.status === 'fulfilled') {
      queueMicrotask(() => {
        try {
          const x = onFulfilled(this.value);
          resolvePromise(promise2, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    }

    if (this.status === 'rejected') {
      queueMicrotask(() => {
        try {
          const x = onRejected(this.reason);
          resolvePromise(promise2, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    }

    // 如果还是 pending,先缓存回调函数
    if (this.status === 'pending') {
      this.onFulfilledCallbacks.push(() => {
        queueMicrotask(() => {
          try {
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        });
      });

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

  return promise2;
};

resolvePromise 辅助函数

这个函数处理 x 的情况,判断它是否是 Promise,决定如何解析并 resolve 或 reject promise2。

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise'));
  }

  let called = false; // 防止多次调用 resolve/reject

  if (x != null && (typeof x === 'object' || typeof x === 'function')) {
    try {
      const then = x.then;

      if (typeof then === 'function') {
        // 认为是 Promise 类型
        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);
  }
}

静态方法:resolve 和 reject

提供快捷方式创建已解决或已拒绝的 Promise。

MyPromise.resolve = function(value) {
  return new MyPromise((resolve) => resolve(value));
};

MyPromise.reject = function(reason) {
  return new MyPromise((resolve, reject) => reject(reason));
};

使用示例

测试我们实现的 Promise:

new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('Hello');
  }, 1000);
})
.then(value => {
  console.log(value); // 1秒后输出 Hello
  return value + ' World';
})
.then(value => {
  console.log(value); // 输出 Hello World
});

基本上就这些。这个实现覆盖了 Promises/A+ 的核心机制:状态管理、异步任务队列(使用 queueMicrotask)、then 的链式调用和 resolvePromise 的递归解析。虽然省略了一些边界检查和更复杂的兼容逻辑,但它能帮助你理解 Promise 背后的运行原理。

理论要掌握,实操不能落!以上关于《手写Promise源码,深入解析Promises/A+规范》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>