Wait for ajax response before moving to the loop

Asked

Viewed 636 times

2

How could I make the following code work? On the Sleep.php page I have 2 seconds waiting only for the test. I need the next for run only after the full execution of the function corrige.

I tried to use "Promises" but I can’t understand how to use in each element of for.

$(".start").on('click',function(e){            
 var anexo = document.getElementsByClassName('anexos');            
 for (var i = 0; i < anexo.length; ++i) {
  /* aqui eu quero que cada execução do FOR 
   * seja executada somente após o término
   * da função "corrige"...
  */     
  corrige(anexo[i]);
 }            
});

function corrige(func){
 $.ajax({
  type: 'POST',                    
  url: 'sleep.php',
  dataType: 'json'
 });    
}
  • You want to "pause" the loop every iteration, is that it? Explain better what you’re trying to do. What’s going to happen inside the loop?

  • It would not pause... but wait for the "fix" function to be finished and only after that, continue the loop... inside the FOR will the "fix" function, forgot to put there...

2 answers

2


Not using es8, da para pensar em recursividade:

$(".start").on('click',function(e){            
 var anexo = document.getElementsByClassName('anexos');    
 corrigir(anexos);       
});

function corrigir(anexos) {
 corrige(anexos, 0, anexos.length - 1);
}

function corrige(anexos, i, max){
    if(i <= max) {
      console.log('atual: ', anexos[i]);
       $.ajax({
        type: 'POST',                    
        url: 'sleep.php',
        dataType: 'json',
        success: function(data) {
          corrige(anexos, ++i, max);
        }
      });  
    }
}
  • Perfect solution with recursiveness, thank you very much!

0

I think that my answer is more a curiosity than useful in practice, due to compatibility problems (it won’t work in IE or old browsers).

function ajaxPromise(indice) {
  return new Promise(resolve => {
    $.post('/echo/html/', {html:'server response ' + indice}).then(resolve);
  });
}

async function asyncLoop() {
  for(let i=0; i<10; i++) {
    var rsp = ajaxPromise(i);
    console.log('after ajax', i,  await rsp);
  }
}

asyncLoop();

https://jsfiddle.net/7cs3buo9/

  • It would be interesting if they justified the downvote, because not working in obsolete browser is no longer a big problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.