循环承诺返回未定义的对象



我创建了一个处理电视节目数组的函数,我正在尝试在新数组中获取每个电视节目的观看进度。

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

我做错了什么?

  • 我正在使用 Trakt.tv API。
  • 原料药信息
<小时 />
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);
});

您需要将从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);
});

最新更新