3

I'm trying to return the values I get in my $http.get but I can't get it to work...

$scope.getDecision = function(id) {
    var defer = $q.defer();
    $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data, status, header, config) {
        console.log(data); //----> Correct values
        defer.resolve(data);
    }).error(function(data, status, header, config) {
        defer.reject("Something went wrong when getting decision);
    });
    return defer.promise;
};

$scope.selectView = function(id) {
     var decision = $scope.getDecision(id);
     console.log(decision); //----> undefined
}

When I call selectView I want to get a decision, but all I get is undefined... Have I misunderstood the promise pattern? :S

Cleaning
  • 65
  • 2
  • 8
  • Yes, promises are still asynchronous. You cannot `return` a simple value – Bergi Apr 24 '15 at 14:02
  • possible duplicate of [Issue with asynchronous function and scope of javascript variable](http://stackoverflow.com/questions/27506970/issue-with-asynchronous-function-and-scope-of-javascript-variable) – thomaux Apr 24 '15 at 14:03
  • 1
    Except for the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572), this should still log a promise object not `undefined`? – Bergi Apr 24 '15 at 14:04

2 Answers2

3

$http itself returns a promise. No need to form your own, just do return $http(...).

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
0

$http returns a Promise anyway, so you don't really need to create your own, but the main reason this isn't working is that you still need to .then your getDecision call in order to wait for the asynchronous operation to complete, e.g.

$scope.selectView = function(id) {
     $scope.getDecision(id).then(function(decision) {
          console.log(decision);
     });
}

To use the existing $http promise:

$scope.getDecision = function(id) {
    return $http({
        method: 'GET',
        url: 'http://127.0.0.1:3000/decision',
        params: {id: id},
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
};
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176