登录
首页 >  文章 >  前端

Promise 中的 then 回调执行顺序如何确定?

时间:2024-12-28 08:04:08 319浏览 收藏

学习文章要努力,但是不要急!今天的这篇文章《Promise 中的 then 回调执行顺序如何确定?》将会介绍到等等知识点,如果你想深入学习文章,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

Promise 中的 then 回调执行顺序如何确定?

promise输出顺序面试题

一道刚从某网站看到的面试题,询问以下代码打印的输出顺序:

promise.resolve().then(() => {
  console.log('start')
  return promise.resolve('end')
}).then(res => {
  console.log(res)
})

promise.resolve().then(() => {
  console.log(1)
}).then(() => {
  console.log(2)
}).then(() => {
  console.log(3)
}).then(() => {
  console.log(4)
}).then(() => {
  console.log(5)
}).then(() => {
  console.log(6)
})

经过分析,可以得到输出顺序为:

start 1 2 3 end 4 5 6

为什么end会在3、4之间?

这是因为 promise.resolve().then() 中 的 return 操作返回了一个新的 promise,并将其加入微任务队列。当第一个 promise 完成后,微任务队列会依次执行,此时第二个 promise 尚未完成,因此会输出 3。之后,第二个 promise 完成,end 输出。

删除return之后

将其改为以下代码:

promise.resolve().then(() => {
  console.log('start')
  promise.resolve('end').then(res => {
    console.log(res)
  })
})

输出顺序变为:

start 1 end 2 3 4 5 6

这是因为 return 会消耗额外的时间,导致第二组 then 的回调函数被推迟执行。

多个 promise 顺序问题

对于以下代码:

promise.resolve().then(() => {
  console.log(1)
}).then(() => {
  console.log(2)
}).then(() => {
  console.log(3)
}).then(() => {
  console.log(4)
}).then(() => {
  console.log(5)
})
promise.resolve().then(() => {
  console.log(6)
}).then(() => {
  console.log(7)
}).then(() => {
  console.log(8)
}).then(() => {
  console.log(9)
}).then(() => {
  console.log(10)
})

输出顺序始终为:

1 6 2 7 3 8 4 9 5 10

这是因为在抛开外部因素的情况下,promise 内部回调函数的执行顺序与其进入微任务队列的顺序一致。

理论要掌握,实操不能落!以上关于《Promise 中的 then 回调执行顺序如何确定?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>