0

So, here is my code

<script>
    var callbackFunction = function(data) {
        var temp = data.query.results.channel.item.condition.temp;
        console.log(temp);
        return temp;
    }
    var $temp = callbackFunction;
</script>
<script src="https://query.yahooapis.com/v1/public/yql?q=select%20item.condition%20from%20weather.forecast%20where%20woeid%20%3D%202487889&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys/&format=json&callback=callbackFunction"></script>

The code "works". I can see the value in the console. But I can't manage to convert the local variable "temp" to the global variable "$temp". I tried this also :

var $temp = callbackFunction();

It doesn't work. I also tried this :

var callbackFunction = (function (data) {...}) ();

This doesn't work for this, but I tried this solution with something else, and it worked.

Thank you!

  • I also tried declaring it before, and then define it in the callback. It just return “undefined” – Charles-François St-Cyr Jul 09 '18 at 17:04
  • Where are you trying to get the value of this variable? It will only be populated after the callback is called, not immediately. See https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Heretic Monkey Jul 09 '18 at 17:06
  • why don't you assign the $temp inside the callback function? – Giannis Mp Jul 09 '18 at 17:09
  • @GiannisMp , I tried that, but I can’t use it outside the callback function. – Charles-François St-Cyr Jul 09 '18 at 17:10
  • @HereticMonkey, I declare my variables in the beginning of the file, and I then use them in various functions. Is there a workaround or something I can do? – Charles-François St-Cyr Jul 09 '18 at 17:12
  • This is the nature of asynchronous code. The code that requires that value should be called only from `callbackFunction` (or called from a function called by that function, etc.). If you're only supporting [recent browsers](https://caniuse.com/#feat=async-functions), you might be able to use [async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) to make it easier on yourself. But if you have to support Internet Explorer, you're stuck. – Heretic Monkey Jul 09 '18 at 17:40
  • See also [this answer from the question I linked to earlier](https://stackoverflow.com/a/28057246). – Heretic Monkey Jul 09 '18 at 17:42

0 Answers0