i'm fairly new to Node.js and by the life of it I can't seem to figure out the whole callback async thing.
what I want to achieve is "relatively" simple if it all where blocking calls.
1) request a list
2) iterate through the elements
3) create new elements for a new list with new element attributes being the result of another request
4) add new element to a new list
specifics:
var originalList = [{
provider: "ABC",
loc: [13.37224, 52.53862],
state: 22
}, {
provider: "CDE",
loc: [13.37124, 52.53262],
state: 33
}, {
provider: "EFG",
loc: [13.37214, 52.53662],
state: 44
}];
var newElement;
var newList = [];
var vLat, vLng;
originalList.forEach(function(element, index, array) {
newElement = {
provider: element.provider,
state: element.state
};
vLat = element.loc[1];
vLng = element.loc[0];
async.parallel([
function(callback) {
var location;
googleMapsClient.reverseGeocode({
latlng: [vLat, vLng],
result_type: ['street_address'],
location_type: ['ROOFTOP', 'APPROXIMATE']
}, function(err, response) {
if (!err) {
var result = response.json.results;
location = result[0].formatted_address;
newElement.location = location;
callback();
} else {
callback(err);
}
});
}
], function(err) {
if (err) console.log(err);
newList.push(newElement);
});
});
I'm omitting the second async function which also makes a Google Maps request and should add that result also to newElement.
I really am struggling why the newElement doesn't get the new attribute (newElement.location). I know that it will be basic.
json arrayseems to be wrong, There is an extra}after every object in the arrayasync.map()and you can pass things from the iterator to the final callback