最近遇到一道面试题,运行出来的答案和想象的有点不一样。
大家一起来看看答案,想想原因呢?
面试题:
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.then() 是微任务的知识,可参考如下文章:
可是,即便了解微任务,但为啥4会在3后执行呢?
是否也想不通(可先上网查询)?
思考?
思考?
思考?
重点就是:对于 return Promise.resolve(4) 的理解
下面来看看大佬 紫云飞 的解释(来源:知乎):
大家以为 Promise.resolve(4) 返回的 promise 对象的状态从 pending 立刻变为 fulfilled,也就是会让再后面的那个 .then 回调立刻进入 microtask 队列。
但其实不是的,如果在一个 pending 状态的 promise 对象(p)的 .then回调里返回一个 promise 对象( p2),或者任意带有 then 方法的对象,引擎会专门起一个额外的 microtask/job 去执行这个 p2的 then 方法,
同时把 p 的 [[resolve]]和 [[reject]]函数作为参数传过去,虽然 p2 已经 fulfilled 了,但它能做的也就是把 [[resolve]] 函数立刻放到 microtask 队列里,这样也就过了两个 microtask,这时 p 才会被 fulfill,p 后面的 console.log('内部第二个then')才会被放入队列。
所以你才看到了慢两拍的表现,只有两拍,如果你 return的是个能同步执行 [[resolve]] 函数的 普通 thenable 对象,那就仅仅会慢一拍,比如你可以返回 { then ( resolve ){resolve()}} 试试。