【问题标题】:output order involve promise, micro task queue in js [duplicate]输出顺序涉及承诺,js中的微任务队列[重复]
【发布时间】:2021-10-14 10:21:09
【问题描述】:

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"

【问题讨论】:

  • 什么是“正确的输出”??
  • 您只能从同一个链中获得已解决的承诺的保证顺序。你所拥有的是两个不相连的 Promise 链,所以你绝对不应该依赖它们以任何特定的顺序排列。
  • 您对微任务的理解是什么(顺便说一句,代码中没有宏任务),以及您预期的输出结果是什么?如果您不解释您认为它是如何工作的,我们将无法帮助您澄清您的误解。

标签: javascript


【解决方案1】:

如果您正在寻找此输出:

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

然后在您的第一个 .then( 中返回 Promise,如下所示:

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")
})

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2019-01-23
    • 2019-05-06
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    相关资源
    最近更新 更多