Search code examples
jqueryscoping

Scoping Issue: value is lost


I am trying to return a JSON object from a method (pollServiceForInfo), but it seems to get "lost" when I alert it once the method has finished. I know this is a scoping issue, however I am stumped as how to proceed. Insight would be greatly appreciated.

var id=null;
var jsonData = JSON.stringify( {searchRequest:{coordinates: "1,2,3 1,2,3 1,2,3 1,2,3 1,2,3"}} );
$.post("rest/search",jsonData, function(json){
    id = json.searchResponse.id;
})
.error(function(jqXHR, textStatus, errorThrown){
    alert("obj.responseText: "+jqXHR.responseText + "  textStatus: "+textStatus+"  errorThrown: "+errorThrown);
})
.success(function(data, status, obj){
    // process initial request
    var json = pollServiceForInfo(id);  // method below

    alert(json);  // says undefined
});



var pollServiceForInfo = function(id){
    //alert('id in pollServiceForInfo '+id);    
    var jsonResults;
    $.get("rest/poll/"+id,function(data){
        jsonResults = data.pollResponse;

    }).error(function(){ 
        alert('returning error');
        return "error";
    }).success(function(){
        alert('returning data '+jsonResults);
        return jsonResults;  // is lost after it's returned
    });
};

Solution

  • You can't usefully return from an asynchronous function. Do this instead:

    var pollServiceForInfo = function(id, callback){
        //alert('id in pollServiceForInfo '+id);    
        var jsonResults;
        $.get("rest/poll/"+id,function(data){
            jsonResults = data.pollResponse;
    
        }).error(function(){ 
            alert('returning error');
            callback("error");
        }).success(function(){
            alert('returning data '+jsonResults);
            callback(jsonResults);  // is lost after it's returned
        });
    };
    
    pollServiceForInfo(id, function(json) {
        alert(json);
    });