Return function Angularjs / Javascript

1

How do I retrieve the value of this function using this way:

var teste = getUser(); 

function getUser() {
    userService.getUser(userService.getUserLogged().id).success(
        function(res) {
            return res.data;
        }
    );
}
    
asked by anonymous 08.12.2015 / 12:29

1 answer

1

You will not be able to return a value of syncrona form that is available in an asynchronous method. in this case your best option is to pass a callback function.

So instead of having something like:

function getUser() {
    userService.getUser(userService.getUserLogged().id).success(
        function(res) {
            return res.data;
        }
    );
}

var usuario = getUser(); 
// fazer algo com o usuario.

You need to define a callback function as a method parameter.

function getUser(callback) {
    userService.getUser(userService.getUserLogged().id).success(
        function(res) {
            callback(res.data);
        }
    );
}

getUser(function (usuario) {
    // fazer algo com o usuario.
}); 
    
08.12.2015 / 12:37