简体   繁体   English

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

[英]Return value received in anonymous method inside function

I have a Javascript function that uses the google API. 我有一个使用Google API的Javascript函数。 I want this function to either return the status if there is an error or return the place object if request was OK. 我希望此函数在出现错误时返回状态,或者在请求确定时返回place对象。

My attempt isn't right because I am specifying the return value inside the anonymous method. 我的尝试不正确,因为我在匿名方法中指定了返回值。 I am not sure how to pass up this return value. 我不确定如何传递此返回值。 This is my attempt: 这是我的尝试:

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);

If I declare return value at top of function I still can't return it as the anonymous function does not return instantly so the GetDetail() method returns before it is set. 如果我在函数顶部声明了返回值,由于匿名函数不会立即返回,因此我仍然无法返回它,因此GetDetail()方法会在设置之前返回。 Same with var return = service.getDetails() var return = service.getDetails()

I am not sure on the proper way to write this. 我不确定写这个的正确方法。 I have tried various different things but I am confusing myself now. 我尝试了各种不同的方法,但现在却使自己感到困惑。

How do I get GetDetail() to return the place/status object? 如何获取GetDetail()以返回位置/状态对象?

Thanks for your help 谢谢你的帮助

You need to use callbacks or promises since you can't return from an async call (this is async nature in JS) - here's how you'd use a callback: 您需要使用回调或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!
});

This is why Promises are awesome. 这就是为什么Promise很棒的原因。 AND ES6, ES7, and the new version of Node.js are going to rely on them heavily. ES6,ES7和新版本的Node.js将会严重依赖它们。

You can say: 你可以说:

GetDetail(1234).then(function(info){
  var myInf0 = info;
//then do what you want with it...
  res.render('page', {info: myInfo})
}

or: 要么:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM