I have an array that I am iterating through. For each element, I would like to call another API and assign the result to an attribute of the element that is currently being looked at.
...
sortedRoutes.forEach(function(route) {
let myVariable = false;
var locationdata = {
uri: `url...`,
headers: {
'X-API-KEY': someKey...,
'User-Agent': 'Request-Promise'
},
json: true
};
rp(locationdata)
.then(function(repos) {
...
route.locationInfo = repos.data;
myVariable = true;
})
.catch(function(err) {
...
})
console.log(myVariable); // false
}
The locationInfo
attribute does not get added to each element in the array.
Actually, it turns out any variable that I try to assign in the .then
function does not carry its value outside (I have used the myVariable
to illustrate what I mean).