Ad

Repeating A Function Using Array Of Values

- 1 answer

So, I have the following js function:

var name_list = names; //mike,steve,sean,roger
jQuery.ajax({
    type: "GET",
    url: custom.ajax_url, 
    dataType: 'html',
    data: ({ action: 'some_function', name_list:name_list}),
    success: function(data){    
            alert('success')      
});

Here there is variable that hold an array of values ("mike,steve,sean,roger" separately by a comma).

Now, I want to use the first value to call an ajax (name_list = mike), and once it is done, I want to repeat the same ajax call with the second value (name_list = steve).

Here is my question.

How do I use individual value in the variable and only use the subsequent value when the function (ajax call) is successful?

Thanks!

Ad

Answer

This is one way of doing it:

var name_list = ['mike','steve','sean','roger'];

function recursive(list, done) {
     list = list.slice();
     (function next() {
        var name = list.shift();
        jQuery.ajax({
            type: "GET",
            url: 'url', 
            dataType: 'html',
            data: ({ action: 'some_function', name : name }),
            success: function(data) {    
                console.log('success', name);      
            }
        }).then(list.length ? next : done);
    }());
}

recursive(name_list, function() {
    console.log('all done');
});
Ad
source: stackoverflow.com
Ad