手写一个符合 Promises/A+ 规范的 Promise 构造函数(包含 resolve、reject、then、catch)

解读

国内大厂(阿里、字节、美团、拼多多)的 Node.js 岗位一面,90 % 会要求“手写 Promise”。
面试官不是考你背代码,而是看三点:

  1. 是否真读过 Promises/A+ 规范(尤其是 2.3 节“Promise 解析过程”);
  2. 是否能在 15 分钟内写出可运行、边界覆盖完整的代码;
  3. 是否能把微任务、异常穿透、值穿透、循环引用等高频坑一次说清。
    现场通常给 15 分钟 + 白板,不允许用 setTimeout 充数,必须 queueMicrotask 或手写微任务队列;catch 方法必须基于 then 封装,不能重复实现。写完后会追问“如何检测合规”——要能说出用 promises-aplus-tests 跑 872 条官方用例。

知识点

  1. 三种状态机:pending → fulfilled / rejected,不可逆。
  2. 值穿透与异常穿透:onFulfilled / onRejected 为函数时才执行,否则“穿透”到下一级。
  3. 微任务:Node 端必须用 queueMicrotask 或 process.nextTick,不能用 setTimeout 宏任务。
  4. 循环引用:如果 x === promise2 必须抛 TypeError。
  5. then 链式返回新 promise,保证异步、保证一次调用。
  6. catch 本质就是 then(null, onRejected)。
  7. 合规检测:npm i promises-aplus-tests && npx promises-aplus-tests 文件名。

答案

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

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 (e) {
    reject(e);
  }
}

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

  const promise2 = new MyPromise((resolve, reject) => {
    const handleMicro = () => {
      queueMicrotask(() => {
        try {
          const x = this.state === FULFILLED
            ? onFulfilled(this.value)
            : onRejected(this.reason);
          resolvePromise(promise2, x, resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    };

    if (this.state === FULFILLED) {
      handleMicro();
    } else if (this.state === REJECTED) {
      handleMicro();
    } else {
      this.onFulfilledCallbacks.push(() => handleMicro());
      this.onRejectedCallbacks.push(() => handleMicro());
    }
  });

  return promise2;
};

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise'));
  }
  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);
  }
}

MyPromise.prototype.catch = function (onRejected) {
  return this.then(null, onRejected);
};

// 合规导出
MyPromise.defer = MyPromise.deferred = function () {
  const d = {};
  d.promise = new MyPromise((resolve, reject) => {
    d.resolve = resolve;
    d.reject = reject;
  });
  return d;
};

module.exports = MyPromise;

跑官方测试:
npm i promises-aplus-tests
npx promises-aplus-tests my-promise.js
872 条全部通过即合规。

拓展思考

  1. 微任务降级:若运行环境低于 Node v11,queueMicrotask 不存在,可降级为 process.nextTick,但需向面试官说明 nextTick 比 Promise 优先级高,会略微打乱观测顺序。
  2. 静态方法:Promise.resolve / reject / all / allSettled / race 是二面高频续问,建议提前实现。
  3. 性能优化:大量 then 链式场景下,onFulfilledCallbacks 数组可换成单链表,减少闭包内存。
  4. TypeScript 版本:国内部分团队要求源码即 TS,需把 then 泛型化,保证链式类型推导。
  5. 与 async_hooks 结合:在 Node 端可埋点 init/before/after 钩子,实现全链路异步追踪,展示你对企业级可观测性的理解。