[英]How to get values from callback functions in NodeJS?
我是NodeJs的新手,我正在制作一個快速的應用程序來學習,在這個應用程序中我想利用用戶提供的經度和經度通過節點地理編碼器反轉地理編碼地址,下面的代碼允許我保存數據庫中的模型。 我想讓用戶知道過程是否成功,我如何從保存功能中獲取狀態值並將其傳遞給響應?
提前致謝。
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);
});
這就是異步代碼的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.