Simulate ajax synchronous in a loop

1

We already know that ajax is asynchronous and the only way to do it synchronously is by setting the async: false option.

What I want to do is something like that

for (var fact in facturas ) {
    sendEmailAJAX(facturas[fact]);
    console.log(fact+ "enviado!!!");
}

I want you to go calling sendEmailAJAX one at a time and not all at once.

I can do it with async:false but the browser is blocked.

I can not think of how to solve this problem.

    
asked by Takyo 04.04.2017 в 17:47
source

1 answer

1

You could set a time to re-run the code that is in your for , something like this:

for (var fact in facturas ) {    
    setInterval(function(){
        sendEmailAJAX(facturas[fact]);
        console.log(fact+ "enviado!!!");
    }, 5000);
}

where 5000 specifies 5 seconds of waiting to send the next one and you can modify it to your liking depending on the time used for each operation.

UPDATE 1

for (var fact in facturas ) {
    $.when(sendMailJs(fact)).done(continue);
}
function sendMailJs(){
    sendEmailAJAX(fact);
    console.log(fact+ "enviado!!!");
    return true;
}

for more information check the documentation of $ .when () on the official page of jquery

    
answered by 04.04.2017 в 18:04