How to make multiple HTTP requests within a loop with JS

0

What I am trying to do is: I need to send a request where an ID should be returned, once I retrieve this ID, I trigger another request that finally registers the data on the server. This processing must be done in a repetition structure that iterates my to-do list where, at each iteration, two requests must be made to fetch another user's id to register a task.

Ex:

function consulta_retorna_id(nome){
    return get_id(nome);
 }

 function insere_tarefa(id, tarefa){
    set_tarefa(id, tarefa);
 }

 //person = arquivo json local
 for (x in person) {

    var id = consulta_retorna_id(person[x].nome);
    insere_tarefa(id,person[x].nome);

}

My challenge is to work with the asynchronism of http calls, since the requests happen independently but must obey a flow of execution in which I first retrieve the id then insert

    
asked by anonymous 20.10.2018 / 22:27

1 answer

0

One solution I use is callback functions, which are only executed after the request succeeds, see the code below as it would be.

function get_id(nome, callback) {
  $.ajax({
    /* sua configuracao ajax*/
    success: function() {
      var id = /*sua configuracaopara obter id*/ ;

      if (callback) {
        callback(id)
      }
    }
  });
}

function insere_tarefa(id, tarefa) {
  set_tarefa(id, tarefa);
}

for (x in person) {

  get_id(person[x].nome, function(id) { //funciton callback
    insere_tarefa(id, person[x].nome);
  });
}
    
22.10.2018 / 16:31