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

标签 javascript es6-promise

.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" 会更高。但他们最终还是出现了。 为什么会发生这种情况?

最佳答案

Do .then, .catch and .finally land in JS Event Loop immediately after being registered or somehow differently?

那些 promise 方法本身永远不会进入队列。任务队列包含 promise react ,基本上是“根据 promise Z 的结果运行回调 X/Y”。 (它们总是成对的 then 回调,因为这是 catchfinally 在内部使用的)。

一旦 Promise 得到解决,就会立即安排这些 Promise react ,或者当 Promise 已经解决时,在 then 调用期间立即安排这些 Promise react 。

If promise callbacks were to be executed in the order they were registered

他们是。但这仅适用于每个 promise 。代码中唯一要附加多个回调的 Promise 是 promise,并且 gA 确实 早于 throwError("B “)。无法保证附加到不同 promise 的回调,因为这些 promise 无论如何都会在不同时间解决。

关于javascript - Promise `.then` 、 `.catch` 和 `.finally` 如何以及何时进入 EventLoop 微任务队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61478388/

相关文章:

javascript - 对象原型(prototype)方法中私有(private)变量的作用域

javascript - 如何嵌套 Promise(Promise.all 内的 Promise.all)

javascript - 使用 ES6 Promise 进行递归的好方法?

javascript - jQuery 更改了 html 页面的内容,但 "View Source"不反射(reflect)更改

javascript - 我们是否应该将 Flash 作为最后的手段?

javascript - 使用按钮的 Node JS 服务器请求

javascript - 然后函数在返回 promise 后不会被调用

javascript - 如何使用 fetch 处理响应 .json 和 .text?

javascript - 如何调试 "TypeError: A promise cannot be resolved with itself"

javascript - 如何使用正确的 isLoading 属性创建默认的 Vuex 状态