将解析值分配给全局变量-Promise [英] assign resolve values to global variables - promises

查看:498
本文介绍了将解析值分配给全局变量-Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定不使用回调,而是决定使用Promise。

Rather than use callbacks, I decided to use promises.

我解析保存价格的变量,然后调用.then来处理它。 / p>

I resolve the variable which holds a price and then I call .then to handle it like this.

SomeAsyncThing("fifa 17").then(function(value){

    console.log("value " + value);
});

如何将值分配给全局变量以在JS中使用?

How can I assign the value to a global variable to use elsewhere in JS?

我缺少明显的东西吗?我尝试定义x = 0;在顶部,然后将值分配给x并从该函数中调用console.log,但得到的不是0,而是分配的值。

Am I missing something obvious? I've tried defining x = 0; at the top, then assigning value to x and calling console.log out of this function but I get 0 rather than the assigned value.

推荐答案


如何将值赋给全局变量以在JS中的其他地方使用?

How can I assign the value to a global variable to use elsewhere in JS?

您不能 1 。或者至少您不应该这样做。您需要先等待诺言兑现,然后才能使用全局变量,但是没有您不知道的诺言。因此,将promise本身分配给全局变量,然后在任何要使用该值的地方都使用 .then()

You can't1. Or at least you shouldn't. You'd need to wait for the promise to fulfill before using the global variable, but without the promise you don't know. So instead assign the promise itself to the global variable, and whereever you want to use the value just use .then().

1:嗯,您甚至可以通过全局声明 var x 来成功实现,但是您意识到了它没有执行您需要的操作

1: Well, you probably even successfully did by declaring var x globally, but as you realised it doesn't do what you need.

这篇关于将解析值分配给全局变量-Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆