Pregunta

I am really new to NodeJs and I am making a quick app to learn, in this app I want to make use of the latitude and longitude provided by the user to reverse geocode the address via node-geocoder, the code below allows me to save the model in the database. I want to let the user know if the process was successful, how may I get the value from the status in the save function and pass it to the response?

Thanks in advance.

app.post('/persons', function (req, res){
  var createPersonWithGeocode = function (callback){
    var lat=req.body.latitude;
    var lon=req.body.longitude;
    var status;
     function geocodePerson() {
        geocoder.reverse(lat,lon,createPerson);
     }
    function createPerson(err, geo) {
        var geoPerson = new Person({
            name:       req.body.name,
            midname:    req.body.midname,
            height:     req.body.height,
            gender:     req.body.gender,
            age:        req.body.age,
            eyes:       req.body.eyes,
            complexion: req.body.complexion,
            hair:       req.body.hair,
            latitude:   req.body.latitude,
            longitude:  req.body.longitude,
            geocoding:  JSON.stringify(geo),
            description:req.body.description,
        });
        geoPerson.save(function (err) {
            if (!err) {
                console.log("Created");
                status="true";
            } else {
                console.log(err);
                status="false";
            }
        });
    }
    geocodePerson();
  }
  return res.send(createPersonWithGeocode());
});
¿Fue útil?

Solución

You can never get the response status if you don't do anything about the callback function. First of all:

geoPerson.save(function (err) {
    if (!err) {
        console.log("Created");
        status="true";
    } else {
        console.log(err);
        status="false";
    }
    callback(status);
});

Now you should provide a callback function that will send the response. Instead of

return res.send(createPersonWithGeocode());

you should do

createPersonWithGeocode(function(status) {
    res.send(status);
});

That's how asynchronous code works.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top