This is the code from my controller
Everything works fine, just not in the order that I specify when I run the promises.
I need to get a price for each record in hotdealArray
, and I get that price by calling the controller priceController.getPrice
.
So to make sure that I get all the prices for all the hotdeals, I add them to my promiseChain
and execute a .then(Promise.all(promiseChain))
BEFORE I execute the callback( { error:false, res } );
to send all results back.
The problem is that the callback sends the data long before the results from my promiseChain have been returned.
var promiseChain = [];
var findAllPrices = function([featuredArray, hotdealArray]) {
return new Promise((resolve, reject) => {
for (var i=0; i<hotdealArray.length; i++) {
promiseChain.push(findPrice(i));
};
resolve({"featured":featuredArray, , "hotdeal": hotdealArray});
})};
var priceController = require('./priceController');
var priceNight = 0;
var findPrice = function(i) {
priceController.getPrice (
{ "body": { "propertyID": hotdealArray[i].property } },
function(result) {
if (result.error == true) {
throw new Error(result.err);
};
priceNight = result.res.priceNight;
hotdealArray[i].priceNight = priceNight;
console.log ("priceNight: " + hotdealArray[i].priceNight);
}
)
};
//
// Run the promises
//
Promise.all([findFeatured(), findLocation(), findNews(), findHotdeal()])
.then(res => {
return(findAllPrices(res))
})
.then(Promise.all(promiseChain)) // <<----- problem!!
.then(res => {
console.log("### === SEND ALL RESULTS === ###")
callback( { error:false, res } );
})
.catch(err => {
callback( { error:true, err } );
}
)
I suspect that for some reason it does not consider priceController.getPrice
as part of the promise chain and that the chain just fires off all calls to priceController.getPrice
and then returns to say "all done with promiseChain, lets continue".
So how can I get it to wait for all the priceController.getPrice
calls to finish returning their data?
via torbenrudgaard
No comments:
Post a Comment