Overwrite asynchronous variable

0

I need to have control of the number of concurrent asynchronous calls from ajax, but I can not overwrite the control variable that holds the number of calls. Every time an asynchronous call is launched it uses the value of the first call ( a copy of the variable before the first call I believe)

Follow my code:

var loaderCallStack = [];
var IsLoaderForSubmit = false;
$(document).ready(function() {

    $('a[href="' + window.location.hash + '"]').trigger('click');

    IsLoaderForSubmit = false;
    $(document).ajaxStart(function() {
        loaderCallStack.push("handle");
        if (IsLoaderForSubmit)
        {
            //váriaveis que preciso alterar  aqui
        }
    });
    $(document).ajaxComplete(function() {
        loaderCallStack.pop();
        if (IsLoaderForSubmit && (loaderCallStack.length === 0))
        {
            //váriaveis que preciso alterar  aqui
            IsLoaderForSubmit = false;
        }
    });
});

My question is, can I control the number of calls while maintaining the asynchronous code? I know that putting it as synchronous would be an option, but at the moment it is not what is desired.

The solution I thought was to stack something every time the call is made and unpack when it's done. If that happens with a control variable this can not be done, is there another way?

    
asked by anonymous 03.03.2016 / 18:36

1 answer

1

pmargreff, I tried to simulate your problem, I noticed that ajaxStart is called only on the first request, so use ajaxSend .

JSFiddle

var qtdRegistros = 0;    
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    qtdRegistros++;
    if (qtdRegistros> 1) {
        jqXHR.abort();
    }
});
$(document).ajaxComplete(function(event, jqXHR, ajaxOptions) {
    qtdRegistros--;
});

Q: I did not create a direct example in the OS, because to simulate this problem I had to use the JSFiddle API to simulate requests.     

03.03.2016 / 19:13