0

I'm having issues redefining tPrice further below it seems to still return as 0 and I need it to pull from json. Is it that the inner inner function redefined the tPrice and how do I force return outside as a global.

if (tPrice == 0 ){
    var xhr3 = new XMLHttpRequest();
    xhr3.open("GET", "APICALL",true);
    xhr3.send();

    xhr3.onreadystatechange = function() {
      if (xhr3.readyState == 4) {
        var resp3 = JSON.parse(xhr3.responseText);
        tPrice = resp3.USD;
        }
    }
}
Blynn
  • 1,411
  • 7
  • 27
  • 48
  • 1
    Looks like a duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs May 05 '18 at 19:39
  • where are you reusing this value ? I mean after you've got response this would be set to new value – Muhammad Usman May 05 '18 at 19:41
  • It's passing into a template and I was hoping to reassign it if it == 0 – Blynn May 05 '18 at 19:42
  • 1
    Probably because your request is asynchronous and `tPrice` might not have been updated when you read/access its value. – Terry May 05 '18 at 19:42
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Patrick Roberts May 05 '18 at 19:53
  • It's not a variable scoping issue. There is only one declaration of a variable named `tPrice` - the declaration is not overridden, and it does get set to the new value. (A variable is only declared by the keyword `var`, or possibly `let` or `const` in later versions of javascript, or when it appears as an argument to a function.) As other comments have said, the problem is that the `onreadystatechange` handler is called asynchronously, i.e. it doesn't happen until well after whatever code you've written below the function definition. – David Knipe May 05 '18 at 20:07

0 Answers0