0

I have ajax requests in my for loop and I am trying to print the value of iteration index 'i' in each iteration. I am using a wrapper function(which is suggested in many posts) in for loop to execute the ajax. But when I print the value of console, it gets printed in random manner. And each time I run the for loop, it is different.

Here is my for loop and wrapper function

 get_process_status(){                  //new

        for(var i=0; i<this.state.current_auto_video_jobs_urls.length; i++){
            this.get_auto_video_jobs_array(i)
        }
    }

//wrapper function

    get_auto_video_jobs_array(i){
        var that = this;
        var settings_3 = {
            "async": true,
            "crossDomain": true,
            "url": that.state.current_auto_video_jobs_urls[i],
            "method": "GET",
            "headers": {
                Authorization: "Token " + that.props.token_Reducer.token
            },
            success: function (response, textStatus, jQxhr) {
                console.log("success")
                console.log("value of i is " + i)
            },
        }

        $.ajax(settings_3).done((response) => {
            auto_video_jobs_array.push(response)
            if(i == that.state.current_auto_video_jobs_urls.length -1 ){
                console.log("i reached last value")
                that.setState({current_auto_video_jobs: auto_video_jobs_array})
                console.log("current jobs are" + that.state.current_auto_video_jobs)
            }
        });
    }

Console output

enter image description here

You can see in 2 times, value of i printed was on different sequence. Why can't it be just 0 to 9 in sequence every time loop runs?

EdG
  • 2,243
  • 6
  • 48
  • 103

1 Answers1

0

Because AJAX, as is name suggest (Asynchronous Javascript And XML), is asynchronous, meaning it will not run sequentially. For your code to work you have to put the loop inside the success handler of the Ajax request

Plotisateur
  • 476
  • 9
  • 23