Wait for ajax response before continuing in the loop

2

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

I tried to use promises but I can not figure out how to use them in every 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'
 });    
}
    
asked by anonymous 06.09.2017 / 01:40

2 answers

1

Without using es8, think of recursion:

$(".start").on('click',function(e){            
 var anexo = document.getElementsByClassName('anexos');    
 corrigir(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 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);
        }
      });  
    }
}
    
06.09.2017 / 07:10
0

I think that my answer is more of a curiosity than useful in practice, due to compatibility issues (it will not work in IE or in older 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();

link

    
06.09.2017 / 05:03