promises: fetched data weirdnesses

时间:2018-02-03 09:01:58

标签: javascript fetch

I have a very hard time understanding the following problem :

let pets;

fetch("https://learnwebcode.github.io/json-example/animals-1.json")
.then(rawData => rawData.json())
.then(jsonData => pets = jsonData);

const animalsNames = pets.map(x => x.name);

console.log(animalsNames);

or

const pets = []

fetch("https://learnwebcode.github.io/json-example/animals-1.json")
.then(rawData => rawData.json())
.then(jsonData => pets.push(...jsonData))

const animalsNames = pets.map(x => x.name);

console.log(animalsNames);

both of them are going to return undifined or give me an empty array however I try... The weird thing is that if I simply typed this in the console afterward :

pets.map(x => x.name);

It would give me the array of the animals names. It makes me mad... I appologize in advance for I have been researching the problem and found answers on the subject, but I can't seem to apply them to my problem. There is something I am missing here. credits to LearnWebCode for his json file ^_^

Thanks folks

1 个答案:

答案 0 :(得分:1)

This happens because a fetch call is asynchronous. Fetching a website takes time, but instead of the whole Javascript-file having to wait for this to finish (as in Python for example) it keeps on executing the rest of the program in the mean time.

So how do you process the returned value, once the fetch is done?

Enter Promises. You should really read this article to get an understanding of asynchronous programming in Javascript. Basically all you need to do is process your data after it has been fetch like so:

fetch("https://learnwebcode.github.io/json-example/animals-1.json")
.then(rawData => rawData.json())
.then(jsonData => {
    const animalNames = pets.map(x => x.name);
    console.log(animalsNames);
})