I am loading results in batches and looking for a solution that will prevent the screen from freezing until all my ajax calls have returned. Someone recommended using async promises (is that the correct solution?) but I don't understand how the syntax works to pass parameters between the chained calls.
It's the equivalent of this looped chain of many ajax calls except I need all calls to depend on the result from the previous call (in this example the loops for url1 all fire simultaneously which is not what I want). The run should end when the returned boolean "proceed" (from any of the ajax calls) is false, not when the last loop and url have been reached.
for (let i = 0; i < numLoops; i++) {
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: i}),
success: function(response) {
var result = JSON.parse(response);
if(result['proceed']){
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
if(result['proceed']){ ... and so on
I am trying to use jquery .when .then promises with these functions:
function First(loop, proceed, updated){
if(proceed)
{
$.ajax({
url: url1,
type: "POST",
data : jQuery.param({loop: loop}),
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Second(proceed, updated){
if(proceed)
{
$.ajax({
url: url2,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
function Third(proceed, updated){
if(proceed)
{
$.ajax({
url: url3,
success: function(response) {
var result = JSON.parse(response);
$( "#load" ).html(result['results']);
updated(result['proceed']);
}
});
}
}
I'm having a hard time figuring out how to chain them so that the return from previous function is passed to the next function.
This incorrect syntax describes what I'm trying to do:
var proceed=true;
for (let i = 0; i < numLoops; i++) {
$.when(First(i, proceed, updated); function updated(content) {var proceed=contents;} )
.then(Second(proceed, updated); function updated(content) {var proceed=contents;})
.then(Third(proceed, updated); function updated(content) {var proceed=contents;})
}
How to pass updated proceed from First to Second? How to pass updated proceed from Third to First at end of each loop? I'm not super versed with javacript and would be most grateful for pointers. Thanks!