0

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 "";
    }                      
}
Goul
  • 573
  • 2
  • 5
  • 16
  • What is `parseString`? It will need to change when `EnrichResponse` becomes asynchronous. – Bergi Dec 10 '17 at 22:13
  • "*How I can use the return of callback?*" - [You can't!](https://stackoverflow.com/q/14220321/1048572) – Bergi Dec 10 '17 at 22:14
  • You need to move your `reply.view(...)` into the callback you're passing to `geocoder.reverse()`, i.e. `GetFormattedAddress` (instead of `return`ing) –  Dec 10 '17 at 22:14
  • I just saw that you're looking up multiple coordinates; in that case you need to use `Promise.all()` (`geocoder.reverse()` returns a `Promise`) –  Dec 10 '17 at 23:32

0 Answers0