This is because this callback function(data) {...} ( function(data) {...} ) is launched later when the response is returned ... because it is an asynchronous function. Instead, use the value as soon as you set it, for example:
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 should be all asynchronous behavior, start with what you need when you get it ... what happens when the server responds with data.
Nick craver
source share