我真的是NodeJ的新手,我正在制作一个快速的应用程序,在这个应用程序中,我想利用用户提供的经度和纬度来通过node-geocoder反向对地址进行地理编码,下面的代码允许我保存数据库中的模型。我想让用户知道过程是否成功,如何从保存功能的状态中获取值并将其传递给响应?
提前致谢。
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());
});
最佳答案
如果不对回调函数做任何事情,就永远不会获得响应状态。首先:
geoPerson.save(function (err) {
if (!err) {
console.log("Created");
status="true";
} else {
console.log(err);
status="false";
}
callback(status);
});
现在,您应该提供一个回调函数来发送响应。代替
return res.send(createPersonWithGeocode());
你应该做
createPersonWithGeocode(function(status) {
res.send(status);
});
这就是异步代码的工作方式。
关于javascript - 如何从NodeJS中的回调函数获取值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23321536/