Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating a function using array of values

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!

like image 393
Steve Kim Avatar asked Apr 28 '26 21:04

Steve Kim


1 Answers

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');
});
like image 75
undefined Avatar answered May 01 '26 12:05

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!