Goal: I want to build a class that addresses a news interface and renders the data in the view.
My class (MyNews
) has several methods and one method is fetchNews()
. In this method I get the data from the API. The data from the api should be assigned in a class varaible (news
). In another method (showNews()
) I want to access the data to iterate over it.
My problem: I am beginner in js and I wonder how to query the data. From my understanding the flow is like this: constructor calls fetchNews fetch news first gets a promise and waits until the promise is resolved then the data is assigned to the member but the JS async is running js doesn't wait at this point until the promise is resolved and it continues working with the empty array. This is exactly my problem.
Question What do I need to do or change to fetch the data correctly. So that I can build a HTML list for example.
My JS Code
class MyNews {
news = [];
apiUrl = "https://jsonplaceholder.typicode.com/posts";
constructor() {
this.news;
this.fetchNews();
}
fetchNews() {
fetch(this.apiUrl)
.then(async (data) => {
this.news = await data.json();
console.log("A:",this.news.length); // i have results
})
.catch((err) => {
console.log(err)
});
// ...
}
showNews() {
console.log("B:",this.news.length); // empty array
return this.news;
}
}
n = new MyNews;
console.log("C:", n.showNews().length );