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

后端 未结 3 1171
青春惊慌失措
青春惊慌失措 2020-12-01 15:02
function lookupRemote(searchTerm)
{
   var defaultReturnValue = 1010;
   var returnValue = defaultReturnValue;

   $.getJSON(remote, function(data)
   {
      if (da         


        
3条回答
  •  天涯浪人
    2020-12-01 15:52

    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.

提交回复
热议问题