3
I have the following function that performs a request to an API using Angular and I would like the function to return the data, but I am experiencing variable scope problems:
var buscarVagasPorEndereco = function(){
var enderecosVagas = [];
$http.get("dados.json").then(function(response){
enderecosVagas = response.data.enderecosVagas;
});
return enderecosVagas;
};
The
$http.get
performs an asynchronous request. In a very raw response, your Return will be executed before receiving a response from the server, so you will be returning an empty array.– Pedro Camara Junior
Yeah, but I’d have some way to fix it?
– raellage
Where do you want to use this value? you can show more code?
– Sergio
Yes, it’s possible, but we need to see where you’re using this feature. As @Sergio said, try showing a little more of your code.
– Pedro Camara Junior
@dukehplay you can’t 'fix' the asynchronous nature of the language. I also spent a lot of time at first trying to make my applications behave in synchronous streams. If you’ll allow me to give you a hint, accept and use this fact to your advantage.
– OnoSendai