简易 promise 核心逻辑需实现 pending/fulfilled/rejected 三态管理、状态不可逆、构造函数立即执行 executor、then 返回新 promise 并支持值穿透与循环引用检测,上述代码已覆盖这些要点。

要实现一个简易的 Promise 核心逻辑,关键是理解其三个核心状态(pending、fulfilled、rejected)和链式调用机制,不依赖异步调度(如 microtask 队列),先聚焦同步可运行的基础骨架。
状态管理与构造函数
Promise 实例创建时处于 pending 状态,通过 resolve 或 reject 函数切换为 fulfilled 或 rejected。状态不可逆,且只允许改变一次。
- 构造函数接收一个执行器函数
executor,立即同步调用它,并传入自定义的resolve和reject - 内部维护
state(字符串)、value(成功值或失败原因)、onFulfilledCbs和onRejectedCbs(回调队列) -
resolve和reject是闭包函数,仅在state === 'pending'时才更新状态和值,并触发对应队列中的回调
then 方法的基本实现
then 接收两个可选函数:成功回调 onFulfilled 和失败回调 onRejected,返回一个新的 Promise(支持链式调用)。
- 若当前 Promise 已 fulfilled,立即把
value传给onFulfilled,用其返回值 resolve 新 Promise - 若已 rejected,同理处理
onRejected - 若仍为 pending,将回调暂存进对应队列,等后续状态变更时统一执行
- 注意:每个回调都需包裹在
try/catch中,捕获异常并自动 reject 新 Promise
基础链式与值穿透
支持 then().then() 的关键在于每次 then 都返回新 Promise,并正确处理返回值类型:
- 如果
onFulfilled返回的是普通值(非 Promise),新 Promise 以该值 fulfilled - 如果返回的是另一个 Promise,则新 Promise 的状态/值由它决定(即“扁平化”)
- 若返回自身(
return p),需抛出TypeError(循环引用) - 为简化,可先不实现 Promise/A+ 的全部细节(如 thenable 处理),但需保证
undefined、null、基本类型能正常传递
简易可用的最小实现示例
以下是一个可直接运行、不含异步调度的最小可行版本(ES6+):
class SimplePromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.onFulfilledCbs = [];
this.onRejectedCbs = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onFulfilledCbs.forEach(fn => fn());
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = reason;
this.onRejectedCbs.forEach(fn => fn());
}
};
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v;
onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r; };
const promise2 = new SimplePromise((resolve, reject) => {
const handleFulfill = () => {
try {
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
};
const handleReject = () => {
try {
const x = onRejected(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
};
if (this.state === 'fulfilled') {
handleFulfill();
} else if (this.state === 'rejected') {
handleReject();
} else {
this.onFulfilledCbs.push(handleFulfill);
this.onRejectedCbs.push(handleReject);
}
});
return promise2;
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected'));
}
if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then;
if (typeof then === 'function') {
then.call(x, y => resolvePromise(promise2, y, resolve, reject), r => reject(r));
return;
}
} catch (e) {
return reject(e);
}
}
resolve(x);
}
这个实现覆盖了 Promise 最核心的状态流转、链式调用和值透传逻辑,适合学习原理。实际使用中仍需补充 catch、Promise.resolve/reject/all/race 等静态方法,以及对 microtask 的模拟(如用 queueMicrotask 或 Promise.resolve().then)来符合规范时序。











