Synchronous requests

9

I need to make requests, however the first must be GET (getByName) and then execute the rest because they depend on it. It turns out that my code is sending an undefined as the requests depend on the contactsUri that is defined in this first GET request.

By order of alerts, the success of the request get last and the other requests are made. How do I make a "synchronous request" to ensure that only after running getByName will perform 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));
     });

  }; 
    
asked by anonymous 23.07.2015 / 18:15

2 answers

5

As JavaScript is "single thread", it was meant to be asynchronous. Otherwise, it would crash the browser if its synchronous request would take too long and would display that annoying message to the user, asking him to stop the script and thus stopping the execution of his application.

To make requests "synchronously" you use promises . On angled, you can use the Service $ q .

An $ http angular request using promises is summarized as follows:

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: Do not forget to add $ q to controller services.

    
23.07.2015 / 19:12
5

Angled path you can use 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.
});
    
23.07.2015 / 19:24