-1

The following returns "undefined" X 2 from:

countriesUrl is an array of objects.

        console.log(countriesURL2);
        console.log(carMakesUrl2);

        function getDataFromJSON(url){
            var dataJSON;
            fetch(countriesUrl).then(function(data) {
              if (data.ok) {
                data.json().then(function(data) {
                   dataJSON = data;
                   return dataJSON;
                });
              } 
            });
            return dataJSON;
        }

        function displayData(){
            var countriesURL2 = getDataFromJSON(countriesUrl);
            var carMakesUrl2 = getDataFromJSON(carMakesUrl);
            console.log(countriesURL2);
            console.log(carMakesUrl2);
        }

        displayData();

Why is "dataJSON" returned undefined?

Bergi
  • 513,640
  • 108
  • 821
  • 1,164
Alessandro
  • 4,405
  • 15
  • 55
  • 108

1 Answers1

0

Fetch returns a promise, so everything inside your then function is run asynchronously. dataJSON is returned before it is set inside your promise.

olan
  • 3,190
  • 5
  • 21
  • 29