How the Promises works in Angularjs

2

I'm having a bit of trouble understanding Angularjs Promises I have the following code:

function validateUser(name, pw) {

  var status = '';

  var data = {login: name, senha: pw, plataforma: 'APP'};

  $http.post('http://localhost:8100/login', data)
    .then(function(response) {

      console.log(response.data.retorno);

      var status = response.data.retorno;

    }, function(err) {
      console.log(err)
  });
}

function teste(name, pw) {

  var status = validateUser(nome, pw);
  alert(status);
  ...
}

The code works perfectly. But I can not return the response of a $http.post to another function. I can only get the answer of this promise in .then(function(){ ... }

In jQuery we used async: false to solve this problem. Is there anything similar in Angularjs?

    
asked by anonymous 14.10.2016 / 16:16

1 answer

3

You could try doing something like this:

function validateUser(name, pw, callback) {

    var status = '';

    var data = {login: name, senha: pw, plataforma: 'APP'};
    $http.post('http://localhost:8100/login', data)
        .then(
            function successCallback(response) {
                callback(response.data);
            },
            function errorCallback(response){
                callback(response);
            }
        );
}

function teste(name, pw) {
    var status = validateUser(nome, pw, function(result){
        console.log(result);
    });
    alert(status);
    ...
}
    
14.10.2016 / 16:36