数据如何从我的诺言中运行,而无需打电话
因此,我目前正在学习JavaScript中的承诺,我尝试做出我的第一个诺言,并意识到它运行了settimeout()
,即使我没有呼吁开始的承诺,只是通过定义它自己跑了。这是Postlogin
。
const postLogin = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Token: 1234")
}, 2000);
});
^这会记录“ token:1234”,而无需调用postlogin.then()
,
在我调用postlogin1.then(token => console.log(token)之后,这是不运行的。 )});
const postLogin1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Token1: 1234");
}, 2000);
});
postLogin1.then(token => {console.log(token)});
为什么如果我不添加“ RESOLES”
,它会在不调用它的情况下运行代码?
So I'm currently learning about promises in JavaScript, and I tried making my first promise and realized that it ran the setTimeout()
even if I didn't call the promise to begin with, just by defining it, it ran by itself. This being postLogin
.
const postLogin = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Token: 1234")
}, 2000);
});
^ This logs out "Token: 1234" without calling postLogin.then()
Where as this doesn't run until I call postLogin1.then(token => {console.log(token)});
const postLogin1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Token1: 1234");
}, 2000);
});
postLogin1.then(token => {console.log(token)});
Why is it that if I don't add "resolve"
it runs the code without invoking it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
承诺构造师将您传递给它们的功能立即。在您的两个示例中都是这种情况。
如果您在该功能中具有
console.log
,则将调用console.log
。如果您不这样做,那就不会。这就是示例之间的关键区别。然后,
然后
方法只会添加一个事件处理程序,该事件处理程序在解决承诺时将被调用(或者如果已经解决了该事件)。如果您在
中具有
处理程序,则将被调用,然后将函数解析。console.log
,则如果您永远不会调用
Resolve
,则将永远无法解决。您传递给它的功能仍然被调用。Promise constructors call the function you pass to them immediately. This is the case in both your examples.
If you have
console.log
inside that function, then it will callconsole.log
. If you don't, then it won't. That's the key difference between the examples.The
then
method just adds an event handler that will be called when the promise is resolved (or immediately if it has already been resolved).If you have
console.log
in thethen
handler, then it will be called then the function resolves.If you don't ever call
resolve
then it will never resolve. The function you pass to it is still called.