Calling Then Before Or After Promise.all
Solution 1:
I'm wondering if it would make more sense / be more performant
Yes, it would be more performant to process each html request separately and as fast as possible, instead of waiting for all of them and then processing them together in a huge loop. Not only will they processed earlier, you also avoid a possibly long-running loop of heavy processing.
However, the approach also has its drawbacks: it's more complicated to implement. The code you've given is prone to reporting Unhandled Rejection
s if any of the detailPromises
rejects before the database query fulfills, or if any of them rejects and the database query is rejected as well. To prevent that, you'll need to use Promise.all
on all the promises anyway:
var detailPromises = links.map(requestP);
var resultPromise = db.polls.findAsync({}, {title: 1}).then(function(polls) {
var oldPollNames = polls.map(function(item) { return item.title; });
var newPollPromises = detailPromises.map(function(p, i) {
return p.then(function(html) {
// some processing of html
});
});
returnPromise.all(newPollPromies) // not the detailPromises!
.then(function(newPolls) {
// insert newPolls into db
});
});
returnPromise.all([resultPromise].concat(detailPromises)).then(function(r) {
return r[0];
});
Solution 2:
In addition to Bergi's answer I think I found another likewise solution:
var detailPromises = links.map(requestP);
var pollNamePromise = db.polls.findAsync({}, {title: 1}).then(function(polls) {
return polls.map(function (item) { return item.title; });
});
var newPromises = detailPromises.map(function(p) {
returnPromise.join(p, pollNamePromise, function(html, oldPollNames) {
// some processing of html using oldPollNames (newPools.push...)
});
});
Promise.all(newPromises).then(function(newPolls) {
// insert newPolls into db
});
Edit Changed from Promise.all to Promise.join which is available in Bluebird
Post a Comment for "Calling Then Before Or After Promise.all"