1

I have some controller and a function called to obtain some value from a REST WCF web service:

fooBar.controller('fooCtrl',
            function fooCtrl($scope, $http, $resource) {
                $scope.someOnClickEvent = function () {
                GetSomething('a','b','c');
            }
        }
);

function GetSomething($scope, $resource, a, b, c) {
    var ServiceHandle = $resource('some/addr');
    var serviceHandle = new ServiceHandle();

    serviceHandle.a = a;
    serviceHandle.b = b;
    serviceHandle.c = c;

    serviceHandle.$save().then(function (result) {
        console.log('So response should be ready');
        $scope.result = result.ValueFromService;
    });
}

As far as I know $save() returns promise and function inside .then should be called right after response is returned by the server. In my case it's called imediately.

If service returns true I'm going to show some popup, so I need this value to be returned before conditional instruction is executed.

Version of Angular is 1.4.9.

2
  • The documentation does indeed say instance actions return a promise, though the source looks less clear cut (the actual return is return result.$promise || result. The actions also take both success and error callbacks so if the promise isn't working for you maybe you could try those. Commented Feb 5, 2016 at 16:01
  • Thank you @Duncan. I was wrong, .then works like a charm. It's just my lack of education in a field of asynchronous programming ;). Commented Feb 5, 2016 at 16:31

1 Answer 1

2

I've analysed code and its behavior and I'm wrong obviously. Maybe I should delete this question, but I believe it can help someone to understand similar problems.

Function inside .then is in fact called after a response comes from the server. It can be verified using for instance Chrome's developer tools (namely tab network).

However if just after calling GetSomething function we want to access a $scope.result we are making a great mistake. $scope.result will be undefined as long as function inside .then won't be executed. To use a value returned from a service we must do it inside .then function or in a function called by it.

Sign up to request clarification or add additional context in comments.

1 Comment

What you should do is return a promise from GetSomething: specifically return the result of serviceHandle.$save().then() and then any code that needs to wait for completion can do so. Basically make every async function return a promise and you can then either ignore it or use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.