Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function is returning object Promise - nodejs

I am facing an issue that the function getVideoDetails is returning object Promise as an object while I need a simple object which I can return to the other function getTrendingVideos

Can anyone please help?

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;
          });
     }
}
like image 891
Ahsan Khurshid Avatar asked Aug 19 '26 03:08

Ahsan Khurshid


1 Answers

Simply add a Promise.all() call. Your getTrendingVideos() functions is returning a promise already anyway.

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);
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    });
}
like image 147
Bergi Avatar answered Aug 20 '26 17:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!