4

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 : enter image description here

Why is it undefined?

11
  • 2
    This is quite strange. Commented Jul 10, 2020 at 6:27
  • 1
    I know. First i thought it could be because of the async but I've no idea why Commented Jul 10, 2020 at 6:30
  • 1
    this happen with me as well when getting data from a signalr hub and trying to push the values into an array, but in my case i am using filter to get the data and the data is being returned Commented Jul 10, 2020 at 6:35
  • 1
    No, but can you try something like this await this.serieService.fetchCompleteSerie(this.serie).then(seasons => {this.seasons = seasons}); Commented Jul 10, 2020 at 6:56
  • 1
    Trt using a forEach and push your season objects into a new array.then try newArraySeasons[0]. let me know if it works. Commented Jul 10, 2020 at 7:39

1 Answer 1

4

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;
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.