0

I'm new around here and I'm studying JS! In particular JSON! However, I have come across an exercise that I cannot solve, also because I do not understand what I am doing wrong. I need to extract the information about the planets from the StarWars API. So I do the classic fetch and as a result I get the generic information about the planet in the form of a JSON. However, I have to extract the planet name and I get stuck, because when I check the PlanetsData variable, it gives me undefined. Ergo the cycle I wrote to extract the names of the planets doesn't work for some reason. So, my question is:

  1. Why do I get "undefined" for the PlanetsData variable? .. Shouldn't I get the JSON, which displays correctly in the console?
  2. Did I write the cycle correctly? Thanks to who will answer me!

This is my code:

async function getPlanetsData() {
  const planetsData = await fetch ("https://swapi.dev/api/planets").then(data => {
    return data.json()}).then(planets => {console.log(planets.results)}) //  ---> Here i receive the JSON data
    for (let key in planetsData) {
      const someInfo = planetsData.results[key].name
      console.log(JSON.stringify(someInfo)) } //  ---> I don't understand why, but I don't get anything here. There is no response in the console, as if the call did not exist
}   
getPlanetsData()
VLAZ
  • 26,331
  • 9
  • 49
  • 67

2 Answers2

0

It seems that you have the same issue as : read and save file content into a global variable

Tell us if it does solve your issue or not.

(UPDATE)

To answer explicitly to your questions.

  1. First question:

To get value into variable planetsData you can do this:

async function getPlanetsData() {
  const response = await fetch ("https://swapi.dev/api/planets")
  const planetsData = await response.json()
  for (let key in planetsData) {
    const someInfo = planetsData.results[key].name
    console.log(JSON.stringify(someInfo))
  }
}   
getPlanetsData()
  1. Second question:

You didn't write the cycle correctly. To resolve promises it is preferable to choose between using await and.

Hedi Zitouni
  • 179
  • 1
  • 8
  • The second option leads you down a road plastered with problems and potential bugs. On a second look, it is already broken. – Thomas Oct 11 '22 at 14:22
  • You are right. It can't be used as it is. But it is a way to extract the planets value into a global variable totally asynchronously – Hedi Zitouni Oct 11 '22 at 14:52
  • 1. You don't have a very strong argument when your example code is broken. 2. I've seen dozens other attempts exactly like this one and they all ended up being referred to here: [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). *The entire approach is flawed and leads only to problems or straight out bugs!* – Thomas Oct 12 '22 at 00:51
  • Agreed ! I removed part of code that confuses more than it helps. Thanks for your comment – Hedi Zitouni Oct 12 '22 at 12:30
0

You can write the same function in a different and clearer way, check the comments to understand the code!

async function getPlanetsData() {
    
    // 1. Fetch and wait for the response
    const response = await fetch ("https://swapi.dev/api/planets");

    // 2. Handle the response, in that case we return a JSON
    //    the variable planetsData now have the whole response
    const planetsData = await response.json();

    // console.log(planetsData); // this will print the whole object

    // 3. Return the actual data to the callback
    return planetsData;
}

// Function usage 
// 4. Call "getPlantesData" function, when it completes we can call ".then()" handler with the "planetsData" that contains your information
getPlanetsData().then(planetsData => {
    // 5. Do whatever you want with your JSON object
    //    in that case I choose to print every planet name
    var results = planetsData.results; // result array of the object
    results.forEach(result => console.log(result.name));
});
Margon
  • 511
  • 2
  • 10