I need to do thousands of AJAX GET Request – they need to be nested due to their dependency (which means: the next AJAX request uses variables from the response of the previous one).
I managed to request as many times as I could with the example below, but this is a case where I need to do it thousands of time, so impossible to write them like this.
I tried to write loops in many ways, but they all resulted in a non-expected behavior.
$.ajax({
url: 'urllink.com',
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json")
}, success: function(responseJSON){
var jsonResponse = Object.values(responseJSON).pop()
alert(jsonResponse);
$.ajax({
url: 'urllink.com'+jsonResponse,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json")
}, success: function(responseJSON){
var jsonResponse = Object.values(responseJSON).pop()
alert(jsonResponse);
}
})
}
})
4
Answers
You could make a function to make
ajax
calls and another function to call first function in a loop and then you pass the result parameter in each iterationWhat I did was making a
recall
variable that runs itself with the same parameters, and then just check for thecount
to execute itself.Consider a scaffold like the following. Each asynchronous request will run concurrently and spawn it’s own replacement when done. Details are left as an exercise.
The concurrent self-replacing requests can be started N parallel times for independent subproblems. Browsers have a limit of a few parallel requests at a time (eg. 2..8 are common, well short of hundreds). The remote server may have even lower parallel capabilities.
Free typos, iPhone makes this hard 🙁
Assuming that all requests are in order that they all provide a
next
property in response object until the very last one not having that property (or it’s value returns falsy) you should be able to use the following recursive promise chain.End result will be an array of all the
next
values returnedUsage: