Return an array of a function in javascript

Asked

Viewed 1,198 times

1

I’m trying to return an array of a function to assign to a modelin Angularjs. However the return of the function is undefined, but when I give one console.log before returning the array is correct. How do I return the array clientes and assign to the 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;
});

}

  • 1

    And what is the return of the function getClientes? The return used is from the anonymous function passed to the then.

  • I managed to solve by putting the return clientes after the then.

1 answer

1


What you’re doing is an asynchronous request, so it makes no sense to set returns, since you won’t know how long it will take to get the result - and keep your script locked while waiting is a bad idea.

I advise you not to implement logic within the request function, as this will prevent you from using the same request in different parts of the application if necessary. The return of function $http.get is a Promise, so it doesn’t just work to return a value. The best, in my view, would be to pass a function callback as a parameter that will be responsible for handling 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);

This way, when the request is completed, the list of clients' names will be passed as a parameter to exibeNomesClientes, which will display on console, regardless of how long it will take to complete the request, without halting the execution of the script on the page.

Browser other questions tagged

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