Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
161
rated 0 times [  166] [ 5]  / answers: 1 / hits: 40815  / 14 Years ago, wed, november 17, 2010, 12:00:00
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?


More From » jquery

 Answers
34

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.


[#94936] Sunday, November 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;