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.
The problem is that
getJSONis asynchronous.while(params)executes. It’s truthy, so we continue$.getJSONis 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 togetJSONhas not gotten a chance to run yet, soparamsis 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
getJSONcalls.A better solution would be something like this:
By using a function, you take control of the flow and don’t perform another request until the asynchronous callback to
getJSONhas been called.