0

I have a service. Lets say that this returns the string "B". I have the following controller:

$scope.output;
var someVariable = 'A';

$scope.setUpConnection = function (someVariable) {
    $scope.output = createConnection(someVariable);
    console.log($scope.output);
}

createConnection = function (someVariable) {
    var result;
    service.connect(someVariable).then(function success(response) {
        result = response.data;
    }, function error(response) {
        result = 'Error' + response;
    });
    return result;
}

The createConnection() function jumps to the end of the function, not waiting for the .then, returning nothing and as such returning undefined. Can someone explain why it isn't waiting for the promise to finish?

The service isn't the problem, if I replace the return with a direct

$scope.output = response.data;

it works fine. The problem and the reason it's set up like this is that the createConnection() function will eventually take place in a seperate JS file once I get around to moving it, so the solution above won't work. As such I figured I'd need the return statement.

Patrick
  • 302
  • 2
  • 19
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Aug 04 '17 at 10:10

1 Answers1

1

This will not work because at the time you return the result promise is not resolved. you have to unwrap the promise inside the setUpConnection

$scope.setUpConnection = function (someVariable) { 
    service.connect(someVariable).then(function success(response) {
        $scope.output = response.data;
    }, function error(response) {
        $scope.output = 'Error' + response;
    });
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • This worked, however: this function will be called upon by various other controllers. I feel it might be a bit redundant to have to write the setUpConnection function in each of these controllers. Hence why I was aiming for a return statement, since then I could fill a bunch of variables from different controllers with it. – Patrick Aug 04 '17 at 10:38
  • then you can create a callback method to return the response after promise is resolved – Sachila Ranawaka Aug 04 '17 at 10:42