循环Promise返回未定义的对象

时间:2018-06-15 01:03:20

标签: javascript node.js promise

我已经创建了一个处理电视节目数组的函数,我正试图在新数组中获得每个节目的观察进度。

我尝试使用.map.foreachfor循环,Promise.all,但如果我放的话,它总是返回undefined我的.then承诺之外的.map

我做错了什么?

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);
});

1 个答案:

答案 0 :(得分:3)

您需要链接从最终watchedshows.map .then(result创建的承诺,否则result函数将在上述承诺解决之前运行。请尝试使用Promise.all

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);
});