0

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.

2 Answers 2

1

The problem is that getJSON is asynchronous.

  1. while(params) executes. It's truthy, so we continue
  2. $.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.
  3. while(params) executes again. The callback passed to getJSON has not gotten a chance to run yet, so params is unchanged.
  4. Go to step 2.

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, it worked. I just didn't notice that it is async.
Since you seem to be new to Stack Overflow, make sure you tag one of the answers to your questions as answered by clicking the check mark.
0

'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, ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.