JavaScript如何判断Promise已敲定?详解then回调入微队列时机
JavaScript中Promise状态判断与.then()回调入队时机解析
针对你给出的代码示例,我们可以分步骤拆解整个过程:
1. Promise初始化与pending状态
当执行new Promise(executor)时,会立刻同步执行传入的executor函数:
const myPromise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('Resolved promise: '); }, 2000); });
此时:
- executor里的
setTimeout会被推入宏任务队列,等待2秒后执行 myPromise的初始状态为pending(待定),没有保存任何结果值- executor执行完毕,主线程继续往下走
2. .then()回调的暂存
当调用myPromise.then(handler)时:
myPromise.then((resolvedValue) => { console.log(resolvedValue + 'The .then() handler is now running'); });
因为此时myPromise还是pending状态,JavaScript不会立刻执行这个回调,而是将它暂存到myPromise内部的成功回调列表中,等待状态变更后处理。
3. resolve触发状态变更与回调入队
2秒后,宏任务队列中的setTimeout回调开始执行,调用resolve('Resolved promise: '):
- 首先,
resolve函数会将myPromise的状态从pending修改为fulfilled(已兑现),同时保存传入的字符串作为兑现结果 - 接着,JavaScript会把之前暂存在
myPromise中的成功回调函数,推入微任务队列等待执行
4. 微任务执行与回调运行
当前宏任务(setTimeout的回调)执行完毕后,事件循环会优先处理所有微任务队列中的任务:
- 取出
then的回调函数,将之前保存的兑现结果作为参数传入 - 执行回调,输出
"Resolved promise: The .then() handler is now running"
关键总结
- Promise的状态变更由
resolve/reject函数直接触发,调用resolve就会将状态设为fulfilled .then()的回调不会立刻入队,只有当Promise状态变为fulfilled(或rejected)时,才会被推入微任务队列- 微任务会在当前宏任务执行完成后立即执行,优先级高于下一个宏任务
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

