数据如何从我的诺言中运行,而无需打电话

发布于 2025-01-17 23:08:02 字数 713 浏览 2 评论 0原文

因此,我目前正在学习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 技术交流群。

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

发布评论

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

评论(1

唱一曲作罢 2025-01-24 23:08:02

承诺构造师将您传递给它们的功能立即。在您的两个示例中都是这种情况。

如果您在该功能中具有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 call console.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 the then 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.

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