Return an array from a function in javascript

1

I'm trying to return an array of a function to assign to a model in Angularjs. But the function return is undefined , but when I give console.log before returning the array is correct. How do I return the array clientes and assign it to model $scope.clientes ?

angular.module('myApp')
.controller('myCtrl', function($scope, $http){

    $scope.selected = undefined;
    $scope.clientes = getClientes($http);
    console.log(getClientes($http)); //O retorno aqui é undefined

});

function getClientes($http){
$http.get('my/url')
.then(function(response){
    var clientesJson = JSON.parse(response.data);
    var clientes = new Array();

    for(var i = 0; i < clientesJson['clientes'].length; i++){
        clientes.push(clientesJson['clientes'][i]['nome']);
    }
    console.log(clientes);//Aqui é mostrado o array corretamente
    return clientes;
});

}

    
asked by anonymous 05.06.2018 / 15:27

1 answer

1

What you are doing is an asynchronous request, so it does not make sense to set returns, since you will not know how long it will take to get the result - and keeping your script locked while waiting is a bad idea .

I advise you not to implement the logic within the requesting function, as this will prevent you from using the same request in different parts of the application, if necessary. The return of the $http.get function is a promise , so it does not work just to return a value. The best, in my view, would be to pass a callback function as a parameter that will be responsible for manipulating the desired data:

function getClientes(callback) {
  $http.get('my/url')
       .then(response => {
         const json = JSON.parse(response.data)
         const nomes = json['clientes'].map(cliente => cliente['nome']);
         callback(nomes);
       })
}

And, for example, do:

function exibeNomesClientes(nomes) {
  for (let nome of nomes) {
    console.log(nome)
  }
}

getClientes(exibeNomesClientes);

In this way, when the request is completed, the list of client names will be passed as a parameter to exibeNomesClientes , which will display in console , regardless of how long it will take to complete the request, without stopping the execution of the script on the page.

    
05.06.2018 / 15:44