判断 promise 状态变更时机,核心在于区分同步代码执行与微任务队列调度。当 promise 构造函数中的 executor 函数执行时,promise 处于 pending 状态;一旦 executor 中调用 resolve 或 reject,promise 立即变为 fulfilled 或 rejected 状态,但 then/catch 的回调不会同步执行,而是被推入微任务队列,等待当前同步代码执行完毕后由事件循环触发。因此,通过检查 promise 实例的状态属性(如使用第三方库)或在 then 回调中打印日志,可以明确观察到这种异步切换行为。

Executor 内部同步执行对初始状态的影响
在 Promise 创建瞬间,executor 函数是同步执行的。这意味着在 new Promise() 语句结束前,如果 executor 内部调用了 resolve,Promise 就已经从 pending 变为 resolved,尽管此时外部代码尚未运行到后续逻辑。这解释了为什么在 executor 中直接 console.log 能看到状态变化前的中间值,而外部监听则必须等待微任务。

const p = new Promise((resolve, reject) => {
console.log('Executor running');
resolve('done');
});
console.log('After new Promise');
p.then(val => console.log('Then callback:', val));
预期输出顺序为: 1. Executor running 2. After new Promise 3. Then callback: done
微任务队列调度与事件循环的关系
Promise 状态变更后,其关联的 then 回调会被放入微任务队列。JavaScript 引擎会在当前宏任务(如脚本主线程、setTimeout 回调)结束后,清空所有微任务,然后再进行下一轮渲染或宏任务调度。这保证了 Promise 回调总是在当前同步代码块完全执行之后才运行,从而避免了竞态条件。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。

console.log('Start');
Promise.resolve().then(() => console.log('Microtask'));
setTimeout(() => console.log('Macrotask'), 0);
console.log('End');
预期输出顺序为: 1. Start 2. End 3. Microtask 4. Macrotask
基于 resolve 参数类型的具体问题
当 resolve 接收另一个 Promise 作为参数时,当前 Promise 会“穿透”并继承该 Promise 的状态,而不是直接变为 fulfilled。这是判断复杂链式调用中状态变更的关键点:只有当传入的 Promise 自身状态确定后,外层 Promise 才会相应变更。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










