assign resolve values to global variables - promises [duplicate]

白昼怎懂夜的黑 提交于 2020-08-26 13:49:08

问题


Rather than use callbacks, I decided to use promises.

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);
});

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

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.


回答1:


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

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: Well, you probably even successfully did by declaring var x globally, but as you realised it doesn't do what you need.



来源:https://stackoverflow.com/questions/41091818/assign-resolve-values-to-global-variables-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!