gpt4 book ai didi

javascript - 如何从 NodeJS 中的回调函数中获取值?

转载 作者:行者123 更新时间:2023-12-02 17:28:11 25 4
gpt4 key购买 nike

我对 NodeJs 非常陌生,我正在制作一个快速应用程序来学习,在这个应用程序中我想利用用户提供的纬度和经度通过 Node 地理编码器对地址进行反向地理编码,下面的代码允许我将模型保存在数据库中。我想让用户知道该过程是否成功,如何从保存函数中的状态中获取值并将其传递给响应?

提前致谢。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com