Synchronous requests

Asked

Viewed 8,501 times

9

I need to make requisitions, but the first must be a GET (getByNome) and then run the rest because they depend on it. It turns out my code is sending a Undefined because the requisitions depend on contacts which is defined in this first GET request.

By order of the Alerts, the success of the get request takes place last and other requests are made. How do I make a "synchronous request" to ensure that only after running getByNome will run the rest?

$scope.salvar = function () {
    alert("Buscando uri de agencia....");
    var contatosUri = [];
      for(var j = 0; j < $scope.contatos.length; j++){
        var nomeAgencia = $scope.contatos[j].agencia;
        agenciasAPI.getByNome(nomeAgencia).success(function (data){
            alert("Inserir no array.. " + data._links.self.href);
            contatosUri.push(data._links.self.href);
        }).catch(function (error){
          alert(JSON.stringify(error) + "\t" + error);
        });
      }
    alert("Foi inserido no array...." + contatosUri[0]);

    alert("Requests de veiculo...");
    //BUSCAR URI DE AGENCIA
    function buscarAgenciaUri(vetorDados) {
      try {
        var agenciasUri = [];
        for (var i = 0; i < $scope.listaAgencias.length; i++) {
          var json = $scope.listaAgencias[i];
          for (var k = 0; k < vetorDados.length; k++) {
            if (json.nome == vetorDados[k]) {
              agenciasUri.push(json._links.self.href);
            }
          }
        }
      } catch (err) {
        alert(err);
      }
      return agenciasUri;
    }

     var agenciasSeparadas = $scope.opcoes + '';
     agenciasSeparadas = agenciasSeparadas.split(',');
     var agenciasUri = buscarAgenciaUri(agenciasSeparadas);

     //ENVIAR DADOS DE VEICULO
     var jsonObj = {
       nome: $scope.nome,
       tipo: $scope.tipo,
       agencias: agenciasUri,
       contatos: contatosUri
     };

     alert("Enviar json de veiculo..." +JSON.stringify(jsonObj));
     veiculosAPI.postVeiculo(jsonObj)
     .success(function (data, status, headers, config) {
       $scope.nome = null;
       $scope.tipo = null;
     }).error(function (data, status, headers) {
       alert("Erro ao salvar dados do veiculo!");
       alert(data + "\t" + JSON.stringify(data));
     });

  }; 

2 answers

5

Since Javascript is "single thread", it is meant to be asynchronous. Otherwise, it would crash the browser if its synchronous request took too long and would display that annoying message to the user, asking him to stop the Script and thus interrupting the execution of its application.

To perform "synchronous" mode requests you use Promises. At the angle, you can use the Service $q.

A $http angular request using Promises boils down to:

function asyncGET(url) {
    var deferred = $q.defer();
    $http.get(URL).success(function(data,status,headers,config) {
        deferred.resolve(data);
    })
    .error(function(data,status,headers,config){
        deferred.reject(status);
    });

    deferred.promise.then(function(resolve){
        return resolve;
    }, function(reject){
        alert('Erro: ' + reject);
    });
}

PS: Don’t forget to add $q to the controller services.

  • http://answall.com/questions/48011/nos-newbrowsers-agora-n%C3%A3o-haver%C3%A1-mais-requisi%C3%A7%C3%B5es-s%C3%Adncronas Taking advantage of this question, is this a good solution? Force it to be synchronous or there’s something else I can do?

  • Yes. You are not forcing a synchronous request. You are creating a promise that there will be a value there. It is as if you were organizing your What and executing the actions that depend on that promise once they are fulfilled. Your page will load asynchronously and promise-dependent values will appear later. A Promise represents a pending value. You can read a bit about Provers at this link: http://www.mullie.eu/how-javascript-promises-work/

  • What’s up? You figured it out?

  • Yes, in solving the problem it was essential your answer and the Onosendai

  • Promises are not synchronous, they are asynchronous.

5

Via Angular you can make use of chained Promises:

$http.get('http://server.com/endpoint1')
.then(function(response) {
    //seus dados obtidos em http://server.com/endpoint1
    //   estarão em response.data.
    return $http.get('http://server.com/endpoint2');
})
.then(function(response) {
    //seus dados obtidos em http://server.com/endpoint2
    //   estarão em response.data.
    return $http.get('http://server.com/endpoint3');
})
.then(function(response) {
    //seus dados obtidos em http://server.com/endpoint3
    //   estarão em response.data.

    //Adicione seu tratamento final aqui.
});

Browser other questions tagged

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