gpt4 book ai didi

javascript - 为什么在第一个 Promise 解析之后执行链式 Promise 后排队的微任务而忽略链式 Promise?

转载 作者:行者123 更新时间:2023-12-02 17:57:02 28 4
gpt4 key购买 nike

我一直在尝试使用 queueMicrotask() 函数,但我没有弄清楚当回调是微任务时回调的优先级如何。查看以下代码:

function tasksAndMicroTasks() {
const promise = Promise.resolve()

console.log('#1st call')

promise
.then(() => console.log('#3rd call'))
.then(() => console.log('#4th call'))
.then(() => console.log('#5th call'))

queueMicrotask(() => console.log(`I'm microtask from the custom Queue`))


console.log('#2nd call')
}
tasksAndMicroTasks()

那么输出是:

#1st call
#2nd call
#3rd call
I'm microtask from the custom Queue
#4th call
#5th call

然后我继续我的实验并尝试这个:

function tasksAndMicroTasks() {
const promise = Promise.resolve()

console.log('#1st call')

promise
.then(() => console.log('#3rd call'))

promise
.then(() => console.log('#4th call'))
.then(() => console.log('#5th call'))

queueMicrotask(() => console.log(`I'm microtask from the custom Queue`))

console.log('#2nd call')
}
tasksAndMicroTasks()

那么输出是:

#1st call
#2nd call
#3rd call
#4th call
I'm microtask from the custom Queue
#5th call

因此,我的结论是,在第一个解决方案之后以及使用 queueMicrotask(callback) API 注册的任务之后,“链式 promise ”被识别为“第二优先级”。

谁能解释一下执行上下文堆栈如何处理链式 promise 以及为什么链式 promise 与回调的第一个 .then() 注册不同?

最佳答案

.then() 返回的 Promise 是通过回调的结果来解析的,因此它仅在回调被调用后才实现。仅在此时,链式 Promise 的 Promise 处理程序才会被调度到微任务队列上 - 在所有最初在已履行的 Promise 上或通过 queueMicrotask 调度的处理程序之后。

关于javascript - 为什么在第一个 Promise 解析之后执行链式 Promise 后排队的微任务而忽略链式 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75373806/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com