How to make multiple HTTP requests inside a loop with JS

Asked

Viewed 410 times

0

What I am trying to do is the following: I need to send a request in which an ID should be returned, as soon as I recover this ID triggers another request that finally registers the data on the server. This processing should be done in a repeat structure that iterates my task list in which, at each iteration, two requests should be made one to fetch the user id another 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 http calls asynchronism, since the requests happen independently but must obey an execution flow in which first recover the id then inserts

  • Cool and what have you done? Where exactly are you finding some difficulty?

  • I haven’t made the code yet, I couldn’t come up with a strategy to solve this

  • If the id of the user you will be looking for on the first request is the id of the logged-in user, then store it in/Storage instead of making random requests. The site to help specific problems, make the code base structure the way you know, if you have a question, then ask

  • @Guilhermecostamilam No, user is not logged in

1 answer

0

A solution I use are callback functions, which are only executed after the request is successful, see the code below as it would look.

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);
  });
}

  • Thanks for the help! In this case the loop remains asynchronous? in my case I intend to register a task as soon as the previous one is registered which would be synchronous.

  • To make your ajax requests synchronous you can add the async=false attribute in the ajax parameters http://api.jquery.com/jquery.ajax/

Browser other questions tagged

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