Javascript 如何从NodeJS中的回调函数中获取值?
我对NodeJs非常陌生,我正在制作一个快速学习的应用程序,在这个应用程序中,我想利用用户提供的纬度和经度通过node geocoder对地址进行反向地理编码,下面的代码允许我将模型保存在数据库中。我想让用户知道,如果该过程成功,我如何从save函数的状态中获取值并将其传递给响应 提前谢谢Javascript 如何从NodeJS中的回调函数中获取值?,javascript,node.js,callback,geocoding,Javascript,Node.js,Callback,Geocoding,我对NodeJs非常陌生,我正在制作一个快速学习的应用程序,在这个应用程序中,我想利用用户提供的纬度和经度通过node geocoder对地址进行反向地理编码,下面的代码允许我将模型保存在数据库中。我想让用户知道,如果该过程成功,我如何从save函数的状态中获取值并将其传递给响应 提前谢谢 app.post('/persons', function (req, res){ var createPersonWithGeocode = function (callback){ var l
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);
});
异步代码就是这样工作的。让我猜猜:你还必须掌握异步编码的概念吗?(这里有一些句点,使用它们:………)谢谢你的回答Max。我很抱歉句点,但英语不是我的第一语言(尽管不是借口)。再次感谢你的帮助:)不客气。你的英语说到底还不错(但是,嘿,我也不是以英语为母语的人)。谢谢你,真是妙不可言。我在发帖之前也尝试过类似的方法,但不知怎么搞砸了。我将不得不阅读更多关于如何正确使用回调的内容。@Omartores是的,的确,如果您需要使用NodeJS进行编码,这绝对是您必须获得信心的最基本的事情。有了NodeJS,一切都必须是异步的,这使得许多编码人员对这种新的编码理念感到疯狂。不过,有些工具可能会对你有所帮助(即承诺)。