首页 > 解决方案 > 输出顺序涉及到promise,js中的微任务队列

问题描述

new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then(() => {
  console.log("then11")
  new Promise((resolve, reject) => {
    console.log("promise2")
    resolve()
  }).then(() => {
    console.log("then21")
  }).then(() => {
    console.log("then23")
  })
}).then(() => {
  console.log("then12")
})

上面的代码输出如下,当我用 promise 测试我对微任务和宏任务的理解时,我无法得到正确的输出。

// "promise1"
// "then11"
// "promise2"
// "then21"
// "then12"
// "then23"

更具体地说,我对最后 3 个输出感到困惑。谢谢您的帮助!

// "then21"
// "then12"
// "then23"

标签: javascript

解决方案


如果您正在寻找此输出:

// "promise1"
// "then11"
// "promise2"
// "then21"
// "then23"
// "then12"

然后在你的 first 中返回 Promise .then(,如下所示:

new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then(() => {
  console.log("then11")
  return new Promise((resolve, reject) => {
    console.log("promise2")
    resolve()
  }).then(() => {
    console.log("then21")
  }).then(() => {
    console.log("then23")
  })
}).then(() => {
  console.log("then12")
})

在您的second 之后返回链return中最后一个所做的 Promise 。您的最后一个将等待 ,然后执行。.then(new Promise.then(then23 .then(


推荐阅读