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

How can I assign a value to 'result[i]' array from inside '.then()'. For now it comes out to be empty. Error that returns is Promise { <pending> }. Thanks in advance.

Saurabh Verma
  • 119
  • 2
  • 2
  • 11
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kirk Larkin Aug 28 '18 at 13:57

1 Answers1

0

Promise.all() will resolve when a passed array of promises has resolved.

The code should collect the promises made by getVideoDetails() and return a promise to perform those requests...

  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);
    });
  }
danh
  • 62,181
  • 10
  • 95
  • 136