我不确定如何用单独的承诺包装/抽象承诺。
我想要实现的工作流程
这是我到目前为止所得到的。
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) })