简体   繁体   English

递归函数返回后的函数调用

[英]Function call after recursive function returns

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. 我在某些服务类中具有递归函数,以删除一些json元素,并且一旦删除它们,我就必须调用为更新注册的回调。

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 但是它给我的错误是TypeError: Cannot read property 'then' of undefined

Thanks 谢谢

You're assuming removeScripts() returns a Promise, it does not. 您假设removeScripts()返回Promise,但没有返回。 removeScripts() is sync, so just add statements after it normally. removeScripts()是同步的,因此通常在其后添加语句。

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 . 您需要使用Deferred API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM