开发者

JavaScript variable reference problem

开发者 https://www.devze.com 2023-03-24 04:29 出处:网络
I\'m trying to send a request and then in callback function, change the parameters and then send the request again. Something like this:

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 contai开发者_StackOverflowns 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 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号