Reputation: 301
I'm trying to send a request and then in callback function, change the parameters and then send the request again. Something like this:
function sendRequest() {
params = {param1:'value', param2:'value'};
while(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
else
params = null;
});
}
}
But params
never changes and the while
loop continues for ever. It seems to be a reference problem; but I can't figure out how to solve this. Thanks in advance.
Upvotes: 0
Views: 340
Reputation: 6417
'params' is a closure variable. The value of params changes at a later time in the callback when the asynchronous ajax call's response arrives, but your while loop is keeping the JS engine busy that the callback isn't going to get called ever.
Either you could keep calling the same function in the response callback or you can use async: false
like this $.ajax({ async: false, ...
Upvotes: 0
Reputation: 54593
The problem is that getJSON
is asynchronous.
while(params)
executes. It's truthy, so we continue$.getJSON
is called. The function passed to it will not be called at this time. It's just queued to the subsystem that later will perform the actual request - asynchronously.while(params)
executes again. The callback passed to getJSON
has not gotten a chance to run yet, so params
is unchanged.In other words, you created an infinite loop, since the system that processes the queued callback function never gets to execute because of the infinite loop. All you end up doing is creating a infinitely long list of queued getJSON
calls.
A better solution would be something like this:
function sendRequest(params) {
$.getJSON("url", params, function(data) {
if(data contains something important)
params.foo = bar;
sendRequest(params);
else
params = null;
// Probably do something like requestChainFinished(params);
});
}
sendRequest({param1:'value', param2:'value'});
By using a function, you take control of the flow and don't perform another request until the asynchronous callback to getJSON
has been called.
Upvotes: 1