[英]Return value received in anonymous method inside function
我有一个使用Google API的Javascript函数。 我希望此函数在出现错误时返回状态,或者在请求确定时返回place对象。
我的尝试不正确,因为我在匿名方法中指定了返回值。 我不确定如何传递此返回值。 这是我的尝试:
function GetDetail(id)
{
var service = new google.maps.places.PlacesService($('#results').get(0));
service.getDetails({
placeId: id
}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
return place;
}
else {
return status;
}
});
}
var myReturnObj = GetDetail(1234);
如果我在函数顶部声明了返回值,由于匿名函数不会立即返回,因此我仍然无法返回它,因此GetDetail()方法会在设置之前返回。 与var return = service.getDetails()
我不确定写这个的正确方法。 我尝试了各种不同的方法,但现在却使自己感到困惑。
如何获取GetDetail()以返回位置/状态对象?
谢谢你的帮助
您需要使用回调或Promise,因为您无法从异步调用中返回(这是JS中的异步特性)-使用回调的方法如下:
function GetDetail(id, callback) {
var service = new google.maps.places.PlacesService($('#results').get(0));
service.getDetails({placeId: id}, function (place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
callback(place);
} else {
callback(status);
}
});
}
GetDetail(1234, function(resp) {
var myReturnObj = resp; //do your work in here!
});
这就是为什么Promise很棒的原因。 ES6,ES7和新版本的Node.js将会严重依赖它们。
你可以说:
GetDetail(1234).then(function(info){
var myInf0 = info;
//then do what you want with it...
res.render('page', {info: myInfo})
}
要么:
GetDetail(1234)
.then(function(info){
return db.insert({_id: info.id, stuff: info.arrayOfStuff})
.then(function(){
return db.findOne({_id: info.id})
.then(function(){
res.render('page', {id: info.id})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.