2

I want to do some treatment once the function I called, which performs a call to the server, is done.

I tried :

vm.myFunction().$promise.then(function(){
    //some treatment done once vm.myFunction() is finished....
})


vm.myFunction = function(){
    var deferred = $q.defer();
        myResource.get(function(result){
            vm.results = result;
            for (var i=0; i<vm.results.length;i++){
                if (vm.results[i].state == 'open'){
                    deferred.resolve();
                    return deferred.promise;
                }
            }
        })
};

But I ma getting a

angular.js:13294 TypeError: Cannot read property '$promise' of undefined

How can I do that?

3
  • return myResource.get(func...... Commented Dec 19, 2016 at 8:49
  • you are not returning anything from the function return myResource.get(), also there is no case where you will reject it - just to make sure you dont end up in infinite wait or add a timeout Commented Dec 19, 2016 at 8:55
  • You just return that myResource.get(//code) function. And no need to use $promise as you are already returning the promise. Commented Dec 19, 2016 at 9:03

3 Answers 3

3

You must return deferred.promise at the end of the function.

vm.myFunction = function(){
    var deferred = $q.defer();
    myResource.get(function(result){
        vm.results = result;
        for (var i=0; i<vm.results.length;i++){
            if (vm.results[i].state == 'open'){
                deferred.resolve();
            }
        }
    });
    return deferred.promise;
};
Sign up to request clarification or add additional context in comments.

Comments

1

Try this code,

vm.myFunction().then(function(){
  //some treatment done once vm.myFunction() is finished....
})


vm.myFunction = function(){
var deferred = $q.defer();
    myResource.get(function(result){
        vm.results = result;
        for (var i=0; i<vm.results.length;i++){
            if (vm.results[i].state == 'open'){
                deferred.resolve();
            }
        }
    })
   return deferred.promise;
};

Comments

0

thanks to all your answers, I managed to makeit work with :

vm.myFunction = function(){
        return myResource.get(function(result){
            vm.results = result;
            for (var i=0; i<vm.results.length;i++){
                if (vm.results[i].state == 'open'){
                    //....
                }
            }
        })
};

Comments

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.