0

I am having a recursive function in some service class to remove some json elements and once they are removed I have to call the callbacks registered for the updates.

My Code -

    var trimTree = function(){
    removeScripts(tree.children).then(function(){
      angular.forEach(callbacks, function(callback){
        //console.log(callback);
        console.log("Calling callbacks");
        callback();
      });
    });
  }
  function removeScripts(nodes){
    for(i=0;i<nodes.length;i++){
      if(nodes[i].type == 'script'){
        return nodes.splice(i, 1);
      }else{
        return removeScripts(nodes[i]);
      }
    }
  }

But its giving me error as TypeError: Cannot read property 'then' of undefined

Thanks

2
  • 1
    removeScripts doesn't return a promise, so you can't use .then. you might need to use $q to create a promise docs.angularjs.org/api/ng/service/$q Commented Jan 12, 2016 at 10:20
  • 2
    @NitsanBaleli, Promise is not needed in sync operations... Commented Jan 12, 2016 at 10:21

2 Answers 2

4

You're assuming removeScripts() returns a Promise, it does not. removeScripts() is sync, so just add statements after it normally.

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

Comments

-1

You can try:

function removeScripts(nodes){
  var deferred = $q.defer();
  for(i=0;i<nodes.length;i++){
    if(nodes[i].type == 'script'){
      deferred.resolve(nodes.splice(i, 1));
    }else{
      deferred.reject(removeScripts(nodes[i]));
    }
  }
  return deferred.promise;
}

You need to use Deferred API.

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.