How to return function correctly? (Variable Scope)

Asked

Viewed 64 times

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;
};
  • 1

    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.

  • 1

    Yeah, but I’d have some way to fix it?

  • 1

    Where do you want to use this value? you can show more code?

  • 1

    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.

  • @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.

2 answers

3


The $http Angular (and ajax in general) is asynchronous. This means that this function gives feedback before ajax is done and therefore undefined.

What you can do is return to Promise and use chaining .then to call the code that needs that answer.

For example:

var buscarVagasPorEndereco = function(){
    return $http.get("dados.json").then(function(response){
        return response.data.enderecosVagas;              
    });
};

And then you can do:

buscarVagasPorEndereco().then(function(enderecosVagas){
    // fazer algo aqui com enderecosVagas
});

0

Just put the Return inside the get function:

var buscarVagasPorEndereco = function(){
    var enderecosVagas = [];
    $http.get("dados.json").then(function(response){
        enderecosVagas = response.data.enderecosVagas;   

        return enderecosVagas;
    });
};
  • 2

    What’s the difference between having Return inside the get function?

  • Didn’t work :(

Browser other questions tagged

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