简体   繁体   English

为什么我的 Promise 定义会被执行?

[英]Why does my Promise definition gets executed?

I am quite new with Promises and want to know why is it that my Promise definition gets executed without me calling a .then() or resolve on it.我对 Promises 很陌生,想知道为什么我的 Promise 定义在没有调用.then()或解决它的情况下被执行。

var promise = new Promise(function (resolve, reject) {
     console.log("Starting loader");
     resolve();
});

If you run the sample and see the console you will see the 'Starting loader' message.如果您运行示例并看到控制台,您将看到“正在启动加载程序”消息。

https://jsfiddle.net/npqgpcud/ https://jsfiddle.net/npqgpcud/

That is simply how promises are defined.这就是 Promise 的定义方式。 They run their executor function immediately.他们立即运行他们的执行程序功能。 It's in the spec: Promise(executor) , step 9.它在规范中: Promise(executor) ,第 9 步。

This is an instance of the revealing constructor pattern ;这是揭示构造函数模式的一个实例; reading that might help you understand.阅读可能有助于您理解。

That occurs because a promise will execute immediately and synchronously.发生这种情况是因为承诺立即同步执行。

.then() add functions that will be executed when the promise is either fulfilled ( resolve argument) or rejected ( reject argument). .then()添加将在承诺完成( resolve参数)或被拒绝( reject参数)时执行的函数。

with info from comments by @Kirill Slatin来自@Kirill Slatin 评论的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM