我已经创建了一个处理电视节目数组的函数,我正试图在新数组中获得每个节目的观察进度。
我尝试使用.map
,.foreach
,for
循环,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);
});
答案 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);
});