简体   繁体   中英

Return value received in anonymous method inside function

I have a Javascript function that uses the google API. I want this function to either return the status if there is an error or return the place object if request was OK.

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. Same with 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?

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:

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. AND ES6, ES7, and the new version of Node.js are going to rely on them heavily.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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