我遇到一个问题:函数getVideoDetails
将object Promise
作为对象返回,而我需要一个可以返回其他函数getTrendingVideos
有人可以帮忙吗?
export class YoutubeService {
getTrendingVideos() {
var params = {
part: 'snippet',
chart: 'mostPopular',
regionCode: 'GB',
maxResults: '24',
key: config.youtubeApi.key
};
var result = [];
return axios.get('/', {params}).then(function(res){
result = res.data.items;
for (var i = 0; i < result.length; i++) {
result[i] = {
id: result[i].id,
title: result[i].snippet.title,
thumbnail: result[i].snippet.thumbnails.high.url,
publishedAt: moment(result[i].snippet.publishedAt).fromNow()
};
//**Below line Returning a promise object**
result[i] = YoutubeService.getVideoDetails(result[i]);
}
return result;
});
}
static getVideoDetails(video) {
var params = {
part: 'statistics',
id: video.id,
key: config.youtubeApi.key
};
return axios.get('/', {params}).then(function(res) {
var result = res.data;
video.viewCount = result['items'][0].statistics.viewCount;
video.likeCount = result['items'][0].statistics.likeCount;
return video;
});
}
}
答案 0 :(得分:1)
只需添加一个Promise.all()
调用即可。您的getTrendingVideos()
函数已经在返回一个诺言。
getTrendingVideos() {
const params = {…};
return axios.get('/', {params}).then(function(res){
const promises = res.data.items.map(item => {
const video = {
id: item.id,
title: item.snippet.title,
thumbnail: item.snippet.thumbnails.high.url,
publishedAt: moment(item.snippet.publishedAt).fromNow()
};
// Below line is returning a promise object, **and that's ok**
return YoutubeService.getVideoDetails(video);
});
return Promise.all(promises);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
});
}