函数内部匿名方法收到的返回值

时间:2015-08-20 21:04:35

标签: javascript google-places-api

我有一个使用谷歌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()返回地点/状态对象?

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你需要使用回调或承诺,因为你不能从异步调用返回(这是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!
});

答案 1 :(得分:0)

这就是Promises很棒的原因。 AND 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})
})