I am new to Node.js and Javascript in general. I am trying to build a simple web app that would show me a list of properties in a table from some data I consume in a Rest API.
The base data displayed and loading was working. However I'm now trying to derive the address from the geo-coordinates I get and I use an API that is asynchronous. It is forcing me to re-organize my code but can't make it working.
My issue: I don't know how I can use the return of callback geocoder.reverse().
Down the line, the EnrichResponse returns before than the geocoder.reverse() is completed (expected I guess) and my results are eventually never populated to the screen.
Would you please have any suggestion to fix this?
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
var jsonDataUrl = '...';
Request.get(jsonDataUrl, postResponse);
}
});
function postResponse (error, response, body) {
if (error){
throw error;
}
var parseString = require('xml2js').parseString;
var data = parseString(body, {explicitArray: false}, EnrichResponse);
reply.view('index', { result: data });
}
function EnrichResponse(err, jsonData) {
var data = jsonData.recherche.annonces;
for (let i = 0; i < data.annonce.length; i++) {
data.annonce[i].squareMeterPrice = Math.floor(data.annonce[i].prix / data.annonce[i].surface);
data.annonce[i].address = geocoder.reverse({lat:data.annonce[i].latitude, lon:data.annonce[i].longitude}, GetFormattedAddress);
}
return data;
}
function GetFormattedAddress(err, res) {
if(res.length > 0){
return res[0].formattedAddress;
}
else {
return "";
}
}