r/javaScriptStudyGroup • u/[deleted] • Feb 27 '18
[Question] Working with data from a JS promise
So I have this fairly simple video game Web API I am trying to work with. It returns a JSON like this:
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
... (many more 'heroes' in this JSON)
]
}(some of you may know the game at this point).
Then, I address the JSON via JS like so:
const endpoint = 'https://rawgit.com/kronusme/dota2-api/master/data/heroes.json'
let heroes = []
fetch(endpoint)
.then(text => text.json())
.then(data => heroes.push(...data.heroes))
// Tried *.then(console.log(heroes))* which works fine, then tried *.then(console.log(heroes[0].name* which does not work.I have read about promises lately, what they do and how to work with them. What I just don't understand, however, is how to make this above code work from beginning to end. From the above code, I now have all heroes in the array heroes, but I can't work with any of them. I can't console.log/access them with dot notation or anything else, so it is clear that I have a mistake somewhere.
Please advise on how to make the data available to work with, point me in the direction of how to work through this problem because I really want to crack the fetch mystery. I realize this is not stackOverflow, but I haven't gotten the right help there.
Cheers!
1
u/Volv Feb 28 '18 edited Feb 28 '18
Pretty sure the console is tricking you there. It prints an empty array for me. And then when I try to expand it it flags up as having evaluated the contents just now. (A nice trick I dont remember it doing before)
At the point you are trying to log the array the fetching has not necessarily finished. You can test this by waiting a few seconds to log it out and it does work fine.
//setTimeout(() => console.log(heroes), 3000)Here is a comment heavy version of your code that goes through my understanding of Promise flow - Codepen
And here's something a bit more like how I might actually use it - Codepen