您好我试图将用户当前位置存储到MONGODB
,但我无法将结果值设置为 global_variable ?
尝试以下代码
Var global_variable;
getCurrentAddress(location) {
this.currgeocoder.geocode({
'location': location
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("Results:::" + JSON.stringify(results[0]));
**global_variable = results;**
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
但 global_variable 为 undefined
答案 0 :(得分:0)
以下是一个使您的地址调用基于承诺的示例,以便您可以从API调用中获取数据,以便能够传递给MongoDB。当然另一个选择是让你的MongoDB调用回调到geocode
函数本身:
getCurrentAddress = function(location, currgeocoder) {
return new Promise(function(resolve, reject) {
currgeocoder.geocode({
'location': location
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log("Results:::" + JSON.stringify(results[0]));
resolve(results)
} else {
reject('Geocode was not successful for the following reason: '
+ status);
}
})
});
};
getCurrentAddress(/*some location data*/, this.currgeocoder)
.then(function(results) { console.log(results); //pass to MongoDB here})
.catch(function(error) { console.error(error); //handle error})