说说下面代码的输出结果
Promise.resolve().then(() => {
console.log(0)
return Promise.resolve(4)
}).then((res) => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1)
}).then(() => {
console.log(2)
}).then(() => {
console.log(3)
}).then(() => {
console.log(5)
}).then(() =>{
console.log(6)
})
参考答案
代码
Promise.resolve().then(() => {
console.log(0)
return Promise.resolve(4)
}).then((res) => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1)
}).then(() => {
console.log(2)
}).then(() => {
console.log(3)
}).then(() => {
console.log(5)
}).then(() =>{
console.log(6)
})
输出结果
0
1
2
3
4
5
6
详细执行分析(浏览器事件循环‑微任务)MDN Web Do...
关键点:**当then回调返回一个 Promise 对象时,后面的.then不会立刻入微任务队列;要等这个内部 Promise 完成,再额外产生一轮微任务**MDN Web Do...。
- 同步执行完毕,第一轮微任务队列:
then0(打印0)、then1(打印1) - 取出执行
then0:
console.log(0)→ 输出0- return
Promise.resolve(4) - ⚠️ 此时第二个
.then(res=>console.log(res))不能直接进微任务队列,要等待返回的Promise.resolve(4)settle,之后才会把它推入微任务。
- 取出执行
then1:
console.log(1)→ 输出1- 返回普通值 undefined,直接把下一个
then(打印2)加入微任务。
- 微任务队列现在:
then2(打印2)
执行 then2 → console.log(2),把 then3 (打印 3) 入队。
- 执行 then3 →
console.log(3);
同时,前面那个 return Promise.resolve(4) 已经完成,**此时才将 then(res=>console.log(res))(打印 4)推入微任务**。
队列现在:then4(打印4)、then5(打印5)
- 执行 then4 →
console.log(4),无后续。 - 执行 then5 →
console.log(5),把 then6 (打印 6) 入队。 - 执行 then6 →
console.log(6)。
完整打印顺序:0 → 1 → 2 →3 →4 →5 →6
易错坑:很多人误以为返回 Promise.resolve (4),打印 4 会紧跟 0 之后输出变成 0,4,1,2,3,5,6,这是错误。返回 Promise 对象会多 “等待一轮”,让另一侧链式的 then 先走几步MDN Web Do...。对比小实验
如果把 return Promise.resolve(4) 改成普通返回 return 4,输出会变成:0,1,4,2,3,5,6。
返回普通值 vs 返回 Promise 对象行为不一样,返回 Promise 会多一次微任务 “隔代”。
Node 环境说明
在现代 Node(v11+)和浏览器的微任务模型表现一致,输出同样是 0 1 2 3 4 5 6;旧版 Node10 及以前微任务队列行为不同,会有不一样输出,但面试题默认浏览器 / 现代 node 标准。