0

I am using swapi api to get starwars planet data

this is the code:

var data = [];
let url = 'https://swapi.boom.dev/api/planets/';
for (let i = 0; i < 10; i++){
let fetched = fetch(url).then(response => response.json())
.then(json => json.results)
.then(results => data.push(results[i].name))
}

when i run console.log(data) it returns this array: array

now when i try to use its data and run console.log(data[0]) it returns undefined

what shoud i do?

Nikolay Patarov
  • 305
  • 3
  • 11
  • Where are you putting the `console.log`? You're pushing to `data`. Why? – evolutionxbox Sep 09 '21 at 21:06
  • i put console log in the same file. I forgot to add the data=[] in the question – Nikolay Patarov Sep 09 '21 at 21:09
  • Explanation about the behavior you see: You get an **empty array** logged (`Array []`) because you access it while it wasn't filled yet (the promise will resolve only later on). But when you click the arrow in the console, due to **lazy expansion**, you'll see the contents at the point in time when you clicked the arrow, at which point the contents already _will_ have been filled in. – CherryDT Sep 09 '21 at 21:16
  • How can i store the data in an array and then use it? – Nikolay Patarov Sep 10 '21 at 05:17

0 Answers0