In my Node.js app I have a function that loops over an array of URLs and get their values, once loop is done it will return the final value as a Map. Code following.
let getResults = function(urls){
let results = new Map();
let retrievePromises = [];
urls.forEach(function (value, i) {
retrievePromises.push(
restAgent.get(value).then(function(data){
for (let item of data.items) {
let name = item.filter(n => n.name === "somename"); //filter array
let obj = {};
obj.name = item.name;
obj.address = item.address;
results.set(name, obj);
}
}).catch(function(err){
console.log(err);
})
);
});
Promise.all(retrievePromises).then(function(){
return this.results;
});
}
If then I run, console.log(getResults());
it will return undefined
as it is triggered before the function returns results.
How to solve this issue, and since I am new to Promises, any possible improvements to the code? (I know that forEach is not favorable)