I get some seasons of a series from my API.
After that, I want to use seasons[0]
to get the first item in the array.
The problem is that seasons[0]
returns undefined
.
My Code looks like this :
async ionViewWillEnter() {
const seasons = await this.serieService.fetchCompleteSerie(this.serie);
this.seasons = seasons;
console.log(seasons); //output below
console.log(seasons[0]); //undefined
this.selected = seasons[0]; //undefined
}
my service looks like this:
async fetchCompleteSerie(serie: Serie) {
let allSeasons: any;
let serieSeasons = [];
let allEpisodes: any;
let seasonEpisodes: any;
allSeasons = await this.http.get('https://www.myapp.com/api/seasons/', this.httpOptions).toPromise();
await allSeasons.forEach(async season => {
season["episodes"] = [];
if (season.serie === serie.url) {
allEpisodes = await this.http.get('https://www.myapp.com/api/episodes/', this.httpOptions).toPromise();
allEpisodes.forEach(episode => {
if (episode.season === season.url) {
season.episodes.push(episode);
}
});
serieSeasons.push(season);
}
});
return serieSeasons;
}
The console output looks like this :
Why is it undefined
?
The problem is the forEach
which DOES NOT RETURN the promises you try to wait for. For that reason seasons[0]
is still undefined
. But since you log the array to the console and THE SAME array object is used inside your callback, the console refreshes the output after the data arrives. If you clone the array before logging, you will see that its empty console.log([...seasons]);
Simply switch forEach
to map
and use Promise.all
.
async fetchCompleteSerie(serie: Serie) {
let allSeasons: any;
let serieSeasons = [];
let allEpisodes: any;
let seasonEpisodes: any;
allSeasons = await this.http
.get("https://www.myapp.com/api/seasons/", this.httpOptions)
.toPromise();
await Promise.all(allSeasons.map(async season => {
season["episodes"] = [];
if (season.serie === serie.url) {
allEpisodes = await this.http
.get("https://www.myapp.com/api/episodes/", this.httpOptions)
.toPromise();
allEpisodes.forEach(episode => {
if (episode.season === season.url) {
season.episodes.push(episode);
}
});
serieSeasons.push(season);
}
}));
return serieSeasons;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With