0

I am trying to access the data from the capitals array in Javascript but I cannot as it gives me undefined when I alert or console.log it. I can see all the data in my console and can't access it using the index. console_screenshot

    var capitals = []

    countries.forEach(function (item, index) {
        fetch("https://restcountries.eu/rest/v2/alpha/"+countries[index])
        .then((resp) => resp.json())
        .then(function(data){
            capitals[index] = data.capital
        })
        .catch(function(error) {
            console.log(error);
          });
      });
     console.log(capitals)
     alert(capitals)

//This following line doesn't work because my capital[1] shows as undefined
    Document.getElementById("result").innerHTML = capitals[1];
    })
G Man
  • 3
  • 1
  • 1
    Does this answer your question? [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) – evolutionxbox May 02 '21 at 22:07

2 Answers2

0

The problem is that fetch is an asynchronous function, meaning your code will start it, but it will move onto the next line of code before it finishes. So when you console.log it, it just hasn't finished fetching from the link. The way you could overcome this is by (not sure if this is the best solution) doing something like this:

var capitals = [];

// Turn forEach into for loop.

for(var item of countries) {

  // "await" makes the code wait for it to finish to proceed
  
  await fetch("https://restcountries.eu/rest/v2/alpha/"+item)
    .then((resp) => resp.json())
    .then(function(data){
        capitals.push(data.capital);
    })
    .catch(function(error) {
      console.log(error);
    });
}

console.log(capitals);

I haven't tested this code yet, so it may or may not work. Give it a try, though, and I'll see what I can do if the problem persists. Hope this helped! :)

EthanKim8683
  • 46
  • 1
  • 5
  • Tried it but I got `Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules` – G Man May 03 '21 at 07:52
0

The fetch method is asynchronous. It was not finished yet as you tried to access the capitals array. Move this line:

// Changing capital[index] to capitals
Document.getElementById("result").innerHTML = capitals;

into then block:

var capitals = []

    countries.forEach(function (item, index) {
        fetch("https://restcountries.eu/rest/v2/alpha/"+countries[index])
        .then((resp) => resp.json())
        .then(function(data){
            capitals[index] = data.capital
            document.getElementById("result").innerHTML = data.capital;
        })
        .catch(function(error) {
            console.log(error);
          });
      });
     console.log(capitals)
     alert(capitals)
})
G Man
  • 3
  • 1
devrnd
  • 167
  • 5