Promise`.then`,`.catch`和`.finally`如何以及何时进入EventLoop微任务队列?

问题描述 投票:0回答:3

.then.catch.finally是否在注册后立即进入JS事件循环(当JS运行时解释适当的代码时)?

此问题的理论面较少:

我有以下代码(链接到JSBin (online JS execution environment)]

l = console.log

const g = (title) => {
    return (a) => {
      l(title + a)
      return a+1;
    }
};

const gA = g("A ")
const gB = g("B ")

const throwError = (title) => {
    return (a) => {
      l(title + a)
      throw new Error("Error from promise " + title + a)
    }
}; 

promise = new Promise((resolve, reject) => {
  resolve(1)
})

l("Started application")

promise
  .then(gA)
  .then(gA)
  .then(throwError("A "))
  .catch(err => {
    l(err.message);
  })


promise
  .then(throwError("B "))
  .then(gB)
  .then(gB)
  .catch(err => {
    l(err.message);
  })

l("Finish main function")

解析为控制台中的以下输出

"Started application"
"Finish main function"
"A 1"
"B 1"
"A 2"
"A 3"
"Error from promise A 3"
"Error from promise B 1"

如果将按注册的顺序执行promise回调,我希望"Error from promise B 1"在此输出中会更高。但是它们最终出现了。 为什么会这样?

。then,.catch和.final在注册后立即(在JS运行时解释适当的代码时)立即落入JS Event Loop中还是以其他方式有所不同? ......>

javascript es6-promise
3个回答
1
投票

.then.catch.finally是否在注册后立即落入JS事件循环中或以其他方式不同?


0
投票

[当您呼叫resolve()时,承诺完成/拒绝被排队到承诺微任务队列中。然后,当任务开始运行时,附加到promise


0
投票

根据您共享的代码,在下面说答A:

© www.soinside.com 2019 - 2024. All rights reserved.