1

I have a global variable, url2 that is not being updated by a fetch function

Here's my JS code:

var url2 = ""; //Here I define url2, as a global variable
fetch("https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1").then(
    function response(response) {
        return response.json();
    }).then(
    function printOut(myJSON) {
        identification = myJSON["deck_id"];
        url2 = (("https://deckofcardsapi.com/api/deck/" + identification + "/draw/?count=1").toString()); //Here, I change the global variable
        console.log("URL2 in fetch block",url2); //If I print out variable url2, here, it returns the correct response
    }
)
console.log("URL2 after fetch block",url2); //If I print out variable url2 here, however, it returns "" -- like it was previously defined to.

I'm fairly new to JS, and I'm not sure why this happens.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • 5
    the second console.log is executed before the async fetch function finishes, thus printing the empty string that url2 has been set to – Luca Kiebel Apr 11 '18 at 22:50

0 Answers0