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));
});
};
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?
– Daniela Morais
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/
– RafaelTSCS
What’s up? You figured it out?
– RafaelTSCS
Yes, in solving the problem it was essential your answer and the Onosendai
– Daniela Morais
Promises are not synchronous, they are asynchronous.
– danilo