核心是用闭包封装状态与行为,确保 pending→fulfilled/rejected 单向不可逆;state、value、reason 必须私有;executor 同步执行且异常被捕获;then 缓存回调并异步调度;返回新 promise 并按规范解析值与错误。

核心是用闭包封装状态与行为,让 pending → fulfilled/rejected 单向不可逆,且外部无法篡改内部状态。
状态必须私有且不可逆
不能把 state、value、reason 挂在 this 上,否则可被外部修改。应通过函数作用域保存为闭包变量:
- 初始设为
'pending',并声明value和reason为undefined -
resolve和reject函数开头必须检查if (state !== 'pending') return,防止多次调用污染状态 - 状态变更后,所有后续的
resolve/reject调用直接忽略,不报错也不生效
executor 必须同步执行,但 resolve/reject 可异步触发
规范明确要求构造时立即同步运行 executor,但其中的 resolve 或 reject 可由定时器、事件、网络回调等异步调用:
- 不能把
setTimeout(() => executor(...), 0)当作“executor 异步执行”,这是错误理解 - 正确做法:
try { executor(resolve, reject) } catch (e) { reject(e) },确保抛异常也被捕获 - 异步调用
resolve(value)时,仍需先判断state === 'pending'才更新
then 方法要支持缓存与异步调度
当 then 被调用时,若 Promise 还处于 pending,需暂存回调;一旦状态确定,再统一异步执行:
- 用两个数组分别缓存
onFulfilled和onRejected回调 - 状态变为
fulfilled后,用queueMicrotask(或Promise.resolve().then)异步执行所有成功回调 - 同理,
rejected状态下异步执行失败回调,保证符合规范中 “asynchronously” 的要求 - 每次
then都返回一个新MyPromise实例,不是原实例,也不是普通对象
值穿透与错误冒泡靠 then 返回值处理逻辑保障
then 的返回值决定下一个 Promise 的终态,这个逻辑不能简化为“直接返回 x”,而要走标准的 resolvePromise 解析流程:
- 若返回值
x是当前 Promise 自身,抛TypeError拒绝,防死循环 - 若
x是对象或函数,尝试取其then方法;是函数则调用,并用called标志确保只触发一次成功或失败 - 若
x是原始值或 null,直接resolve2(x) - 任意环节抛错,都交由
reject2处理,实现错误向下游自动冒泡










