export class YoutubeService {
getTrendingVideos(country) {
let result = [];
return axios.get('/').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()
};
result[i]= YoutubeService.getVideoDetails(result[i]).then(
(video)=>
{
return video;
}
); //result[i] is not getting resolved
console.log(result[i]); // it returns Promise { <pending> }
}
return result;
});
}
static getVideoDetails(video) {
return axios.get('/').then(function(res) {
let result = res.data;
video.viewCount = result['items'][0].statistics.viewCount;
video.likeCount = result['items'][0].statistics.likeCount;
return video;
});
}
}
如何从'.then()'内部为'result [i]'数组赋值。目前看来它是空的。
返回的错误是Promise {{<pending>
}。
预先感谢。
答案 0 :(得分:0)
Promise.all()
将在传递的承诺数组解决后解决。
代码应收集getVideoDetails()
做出的承诺,并返回执行这些请求的承诺...
getTrendingVideos(country) {
let result = [];
let promises = [];
return axios.get('/').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()
};
promises.push( YoutubeService.getVideoDetails(result[i]) )
}
return Promise.all(promises);
});
}