pgauthier
pgauthier

Reputation: 3

Looping Promise returning an undefined object

I've created a function that is processing an array of TV shows, and I'm trying to get the watched progress for each of them in a new array.

I've tried with a .map, .foreach, a for loop, with Promise.all, but it's always returning undefined if I'm putting the .then outside my .map promise.

What am I doing wrong?


trakt.users.watched({
    username: profile.user.username,
    type: 'shows',
    extended: 'noseasons'
}).then(watchedshows => {
    if (!isEmpty(watchedshows)) {
        //get progress for all watched shows
        watchedshows.map(element => {
            return trakt.shows.progress.watched({
                id: element.show.ids.trakt,
                hidden: 'false',
                specials: 'false'
            }).then(episodeProgress => {
                //if theres a next episode and last watched date is less than a year (discard unwatch shows)
                if (episodeProgress.next_episode && (new Date() - new Date(episodeProgress.last_watched_at)) / 31536000000 < 1) {
                    return element.show.title + ' s' + zeroprefix(episodeProgress.next_episode.season) + 'e' + zeroprefix(episodeProgress.next_episode.number);
                }
            });
        });
    }
}).then(result => {
    console.log(result);
});

Upvotes: 0

Views: 66

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

You need to chain the promises created from watchedshows.map with the final .then(result, else the result function will run before the promises above have been resolved. Try using Promise.all instead:

trakt.users.watched({
  username: profile.user.username,
  type: 'shows',
  extended: 'noseasons'
}).then(watchedshows => {
  if (isEmpty(watchedshows)) return;
  //get progress for all watched shows
  return Promise.all( watchedshows.map(element => {
    return trakt.shows.progress.watched({
      id: element.show.ids.trakt,
      hidden: 'false',
      specials: 'false'
    }).then(episodeProgress => {
      //if theres a next episode and last watched date is less than a year (discard unwatch shows)
      if (episodeProgress.next_episode && (new Date() - new Date(episodeProgress.last_watched_at)) / 31536000000 < 1) {
        return element.show.title + ' s' + zeroprefix(episodeProgress.next_episode.season) + 'e' + zeroprefix(episodeProgress.next_episode.number);
      }
    });
  }));
}).then(result => {
  console.log(result);
});

Upvotes: 3

Related Questions