Rotate array with method WHEN, javascript

0

Well, I have an array of numbers and I need to send each one separately to the server, but I need to wait for all to be executed before executing my final action. I researched and then discovered the method / function WHEN that expects all requests to be closed to execute X function.

The problem is that I do not know how to rotate the entire contents of the array and insert it in that WHEN .. I have no idea ..

See a demonstrative example of it:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){

But my array data does not only have a1, a2, a3 e a4 they can have many more up to "infinites" or just 1 or two items.

My array in case: [1,2,3,4,5,6,6,77,44,23423,234212344]

Ah, I use forEach to run the array

    
asked by anonymous 03.10.2015 / 15:02

1 answer

1

I would say that sending "1 to infinite" ajax requests simultaneously is not a very good idea.

In fact jQUery has a new API for promises and you can pass multiple ajax requests as arguments of $.when() and then run a function when all have been run using .done() .

If it's the case that you have a reasonable number in this array, I think it's a good idea to use $.when() , otherwise I think you should also use .then() , so requests wait for each other.

To answer your question you can do this:

var array = [1,2,3,4,5,6,6,77,44,23423,234212344];
var ajaxArray= array.map(function(nr){
    return $.ajax({url: 'meusite.com', data: nr});
});
$.when.apply($, array).done(function(){
    alert('está pronto!');
    console.log(arguments); // array onde cada elemento corresponde à resposta de cada pedido ajax
});

If you want to chain instead of sending all at once you can use it like this:

var pr = $.Deferred(); // promise vazia
array.forEach(function(el){
    pr = pr.then(function(){
        return $.ajax({url: 'meusite.com', data: nr});
    });
});

pr.then(function(){
    // esta é a ultima chamada e onde podes correr o codigo final
});
    
03.10.2015 / 15:18