关于渴望评估承诺回调的规格

发布于 2025-02-07 20:31:34 字数 525 浏览 3 评论 0原文

是否有有关“渴望”回调的“渴望”的规格 /实现详细信息? 我的意思是,假设我有

var promise = new Promise((resolve) => {
   resolve()
});

console.log(promise); // there is no public field '<state>', but you can see it in the console of the dev tools

我看到Promise已经实现;我期望Promise内部实现会在以下时间拨打Resolve回调,并带有Promise> Promise仍然无法满足的“时间窗口”。

这是对Resolve回调的“急切”评估?这只是实现细节吗?

Is there a spec / implementation detail on how "eager" is the evaluation of the callbacks of a promise?
I mean, let's say that I have

var promise = new Promise((resolve) => {
   resolve()
});

console.log(promise); // there is no public field '<state>', but you can see it in the console of the dev tools

I see that promise is already fulfilled; I was expecting that the Promise internal implementation would call the resolve callback on an following time, leaving a "time window" with promise still unfulfilled.

Is this "eager" evaluation of the resolve callback "by design"? Is this just an implementation detail?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏雨一样淡蓝的深情 2025-02-14 20:31:34

回调传递给了承诺构造器,该构造函数同步执行。因此,当new操作员返回构造的对象时,回调已经运行。

这是由 ecma脚本规范新的Promise(剥夺者)的过程在步骤9中描述了执行程序被调用,并且在步骤11中,返回了构造的承诺对象。

Mozilla贡献者

语法

 新的Promise(executor)
 

参数

 执行程序
 

在构造新的Promise对象的过程中,构造函数要执行的函数。

构造函数回调函数通常用于启动异步过程(通过依靠异步API,例如settemeimout),该过程可以在构造函数回调已经返回的时间时解决承诺。

function executor(resolve) { 
    setTimeout(resolve, 100);
}

var promise = new Promise(executor);

在您的示例中,该回调不依赖于异步API,而是同步调用resolve回调。这意味着,当将构造的承诺对象分配到您的Promise变量时,该承诺已经处于满足状态。

The callback passed to the Promise constructor is executed synchronously by that constructor. So when the new operator returns the constructed object, the callback has already run.

This is by the ECMA Script specification. The procedure for new Promise(excecutor) describes in step 9 that the executor is called and in step 11 that the constructed promise object is returned.

Mozilla Contributors write:

Syntax

new Promise(executor)

Parameters

executor

A function to be executed by the constructor, during the process of constructing the new Promise object.

The constructor callback function is typically used to initiate an asynchronous process (by relying on an asynchronous API, like setTimeout), which can resolve the promise at a time that the constructor callback has already returned.

function executor(resolve) { 
    setTimeout(resolve, 100);
}

var promise = new Promise(executor);

In your example, that callback does not rely an such asynchronous API, but synchronously calls the resolve callback. That means that when the constructed promise object is assigned to your promise variable, that promise is already in a fulfilled state.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文