javascriptjqueryreturn-valuegetjson

How to return a value from a function that calls $.getJSON?


function lookupRemote(searchTerm)
{
   var defaultReturnValue = 1010;
   var returnValue = defaultReturnValue;

   $.getJSON(remote, function(data)
   {
      if (data != null)
      {
           $.each(data.items, function(i, item)
           {
               returnValue = item.libraryOfCongressNumber;
           });
      }
    });
    return returnValue;
}

Why is the returnValue from this function alway equal to the default value set at the beginning of the function and never to the value retrieved from the JSON lookup?


Solution

  • This happens because that callback function (function(data) {...}) runs later when the response comes back...because it's an asynchronous function. Instead use the value once you have it set, like this:

    function lookupRemote(searchTerm)
    {
        var defaultReturnValue = 1010;
        var returnValue = defaultReturnValue;
        $.getJSON(remote, function(data) {           
            if (data != null) {
                  $.each(data.items, function(i, item) {                 
                        returnValue = item.libraryOfCongressNumber;
                  });
            }
            OtherFunctionThatUsesTheValue(returnValue);
         });
    }
    

    This is the way all asynchronous behavior should be, kick off whatever needs the value once you have it...which is when the server responds with data.