Return function Angularjs / Javascript

Asked

Viewed 940 times

1

how do I recover the value of this function using this way:

var teste = getUser(); 

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

1 answer

1


you will not be able to return a value synchronously 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.
}); 
  • Thank you very much Tobymosque, helped me too much, I had forgotten the callback functions.

Browser other questions tagged

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