【问题标题】:Maximum call stack size exceeded in nodejsnodejs中超出了最大调用堆栈大小
【发布时间】:2017-07-02 07:56:00
【问题描述】:

我在 nodejs 中使用事件来实现我的逻辑。 “nextParams”是一个使函数“extractVideo”再次执行的事件。我知道我使用了递归事件循环。我尝试在我的代码中使用 setTimeout(function, 0) 和 setTimeout(function, 1),但仍然出现“超出最大调用堆栈大小”错误,不知道有没有人知道如何解决这个问题,非常感谢!

    videoCrawler.prototype.extractVideo=function(queryStr){ 
       self.on("videoIdArray",function(){
            if(videoIdArray.length){
                self.getVideoInfo(videoIdArray.pop());
            }else{
                self.videomonitor.emit("nextParams");
            }
        });

        self.on("getVideoIdArray",function(videoidarray){
            if(!(videoidarray || videoidarray.length)){
                self.videomonitor.emit("nextParams");
            }
              videoIdArray=videoidarray;
              self.getVideoInfo(videoIdArray.pop());
        });

        self.on("save",function(videodetailinfo){
            if(!videodetailinfo){
                if(videoIdArray.length){
                    self.getVideoInfo(videoIdArray.pop());
                }else{
                    self.videomonitor.emit("nextParams");
                }
            }
            self.saveVideoInfo(videodetailinfo);
        });
        self.on("errorCapture",function(errInfo){             
            if(errInfo.message=="queryStr is not exits"){
                setTimeout(self.videomonitor.emit("nextParams"),1);
            }else if(errInfo.message=="videodetailsinfo is not exits"){
                self.getVideoInfo(videoIdArray.pop());
            }else if(errInfo.message=="videoId is empty"){
                self.getVideoInfo(videoIdArray.pop());
            }else if(errInfo.message=="save fails"){
                self.getVideoInfo(videoIdArray.pop());
            }
        });
        self.getVideoId(queryStr);  
    }

下面是函数

    videoCrawler.prototype.getVideoId=function(queryStr){
      if(!queryStr) this.emit("errorCapture",errInfo);
       //dosomething
       this.emit("getVideoIdArray",videoArray); 
    }

      videoCrawler.prototype.getVideoInfo=function(videoId){
      if(!queryStr) this.emit("errorCapture",errInfo);
       //dosomething
      self.emit("save",videodetails);
      }

      videoCrawler.prototype.saveVideoInfo=function(videodetailsinfo){
       if(!queryStr) this.emit("errorCapture",errInfo);
        //dosomething
       self.emit("videoIdArray");
      }

【问题讨论】:

    标签: node.js


    【解决方案1】:

    对于某些涉及tail calls的问题,您可以在某些版本的Node中开启尾调用优化(从6.5开始,但从8.0开始就没有了!)。

    查看兼容性:

    有关正确尾调用的信息,请参阅:

    对于没有尾部调用的其他情况,您应该使用 setImmediate()process.nextTick(),具体取决于您希望代码运行的时间,而不是使用 setTimeout(),因为它们得到了更好的优化,但 setTimeout() 会仍然避免调用堆栈增长。但是在这里您不会在每次通话时都使用setTimeout(),这可能是问题所在。

    【讨论】:

      猜你喜欢
      • 2013-08-18
      • 1970-01-01
      • 2019-07-05
      • 2017-09-02
      • 2014-02-07
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 2013-08-23
      相关资源
      最近更新 更多