For my for loop, I am trying to make AJAX calls in a specific sequence. The responses need to be stored in an array with elements in the correct order. Despite attempting various solutions from similar questions, none have been successful except setting async: false
. Although I understand that using async: false
is not recommended, I am unsure about alternative methods to achieve sequential responses.
Furthermore, when mapping the array to render elements, some methods resulted in errors stating "cannot read map of undefined."
This is my current approach:
auto_video_jobs_array = [];
for (var i = 0; i < this.state.current_auto_video_jobs_urls.length; i++) {
this.get_auto_video_jobs_array(i)
}
get_auto_video_jobs_array(i) {
var that = this;
var settings_3 = {
"async": false, //this is made false to get array element in right sequence
"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)
}
});
}
I also attempted an alternative implementation which failed and threw an error about being unable to read map of undefined:
//initialize index counter
var i = 0;
var that = this;
function next() {
$.ajax({
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){
++i;
if(i >= that.state.current_auto_video_jobs_urls.length) {
// run function here as its the last item in array
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)
} else {
// do the next ajax call
auto_video_jobs_array.push(response)
next();
}
}
});
}
// start the first one
next();
I am seeking a method to perform async calls while ensuring responses come back incrementally. Using promises has been suggested, although it's unfamiliar territory for me. If promises are the solution, how should I implement them?