1

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.

user1156596
  • 601
  • 1
  • 10
  • 29

1 Answers1

2

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375