CoffeePeddlerIntern CoffeePeddlerIntern - 4 months ago 5
Node.js Question

Collecting Api Returns In An Array

I am making a call to a 3rd party api and I am having problems collecting all the returns and returning them as 1 array In my API. I can see that I am successfully making the calls and they are returning. Due to asynch the final array is returning before it is populated. Is there an elegant solution to handling this?

var itemIds = ['1','2','3','4','5','6']

exports.getItemData = function getItemData(req, res) {
var items = [];
var errors = [];

for(var itemId in itemIds) {
var options = {
uri: itemEndpoint + itemIds[itemId] +'/',
json: true
};

RequestPromise(options).then(function (item){
console.log(item);
items.push(item);

}).catch(function(err){
console.log(err)
errors.push(err);

});
};
res.type('application/json');
res.json(items);
};

Answer

Felix is right. You need to create an array of RequestPromise(options) Promises and then use the Promise.all([array-of-promises]).then(function (<array-of-result-arrays>){}).

So your refactored code will look like this:

var allPromises = [];
for(var itemId in itemIds) {
        var options = {
            uri: itemEndpoint + itemIds[itemId] +'/',
           json: true
        };
        allPromises .push(RequestPromise(options));
}
//so now you have an array of promises in allPromises. Now when they all resolve:
Promise.all(allPromises).then(function (allResults){
       console.log(allResults);
       //do whatever with the results...
   }).catch(function(err){
       console.log(err)
       errors.push(err);
   });

I hope this helps.