gpt4 book ai didi

javascript - 为什么 Promise.resolve().then() 会延迟?

转载 作者:数据小太阳 更新时间:2023-10-29 05:03:51 24 4
gpt4 key购买 nike

我不明白为什么 resoved Promise 延迟 .then() 参数调用?

例子:

var myPromise = Promise.resolve();
console.log(myPromise);
myPromise.then(()=>console.log('a'));
console.log('b');

控制台返回:

> Promise { <state>: "fulfilled", <value>: undefined }
> "b"
> "a"

如果 myPromise 已经完成,为什么 .then() 不立即调用 resolve 函数?

最佳答案

因为,根据规范,promises 在当前执行线程展开并完成返回“平台代码”后调用它们的解析处理程序。这保证了它们总是被异步调用。

因此,当执行线程完成时,您首先会看到 console.log('b'),然后在您看到 console.log(' a').

来自Promises/A+ specification :

2.2.4 onFulfilled or onRejected must not be called until the execution context stack contains only platform code. [3.1].

还有,注意 [3.1]:

Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.

这样做是为了提供一致的执行顺序,因此无论 promise 何时被解决(同步或异步),then() 处理程序总是在与其他代码相关的相同时间被调用。由于许多 promise 是异步解决的,因此无论以何种方式解决,使给定 promise 保持一致的唯一方法是让它们始终异步调用它们的 .then() 处理程序。

关于javascript - 为什么 Promise.resolve().then() 会延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225687/

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