0

I'm not sure how I can wrap/abstract a promise with separate promise.

The workflow I would like to achieve

  • is take a array of objects,
  • foreach object do a lookup using the Google-Trends-Api,
  • perform some basic aggregate functions on each item
  • return an array of objects that include the search keyword and the aggregate data.

This is what I've gotten so far.

var _ = require("underscore");
var Q = require('q');
const googleTrends = require('google-trends-api');


    function update_star_relevance(stars) {

        var deferred = Q.defer();
        stars = [{ "star": { "star_name": "Mila Kunis" } },
                 { "star": { "star_name": "Charlize Theron" } },
                 { "star": { "star_name": "Tom Cruise" } }
        ]

        Q.all(stars.map(row => {
                return googleTrends.interestOverTime({
                    keyword: row.star.star_name,
                    startTime: new Date(Date.now() - (365 * 24 * 60 * 60 * 1000))
                }).then(results => {
                    results = JSON.parse(results);
                    // check if rising in popularity
                    var gains = _.reduce(results.default.timelineData, function (memo, item) {
                        return item.value[0] - memo;
                    }, 0);
                    // check if it is a popular search
                    var avg = _.reduce(results.default.timelineData, function (memo, item) {
                        return (memo + item.value[0]) / 2;
                    }, 0);
                    //console.log(JSON.stringify(row.star));
                    return {
                        "gains": gains,
                        "avg": avg
                    };
                });
            }))
            .then(f => {
                console.log(f);
                //relevant_stars = _.sortBy(relevant_stars, 'gains');
                deferred.resolve(f);
            })
            .catch(function (err) {
                deferred.reject(err);
            });

        return deferred.promise;
    }
      // There is plenty of other chained functions to process the data that I have excluded. 
    update_star_relevance()
     .then(f => { console.log(f) })
zED
  • 338
  • 2
  • 8

0 Answers0