Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当条件满足时,js函数不返回_Javascript_Node.js - Fatal编程技术网

Javascript 当条件满足时,js函数不返回

Javascript 当条件满足时,js函数不返回,javascript,node.js,Javascript,Node.js,下面的代码,我找不出任何问题,但它有时会输出 “'i'不应大于handlers.length” 因为基于人类逻辑,当i等于handlers.length时返回函数,下面的代码永远不应该运行,这个问题真的让我抓狂。之所以会这样,是因为i将在之后的下一次调用中递增,如果(i==handlers.length)返回cb()并成为handlers.length+1 你必须这样做 if (i >= handlers.length) { return cb(); }

下面的代码,我找不出任何问题,但它有时会输出 “'i'不应大于handlers.length”


因为基于人类逻辑,当
i
等于
handlers.length
时返回函数,下面的代码永远不应该运行,这个问题真的让我抓狂。

之所以会这样,是因为
i
将在
之后的下一次调用中递增,如果(i==handlers.length)返回cb()并成为
handlers.length+1

你必须这样做

    if (i >= handlers.length) {
        return cb();
    }

或者类似的情况。

最简单的假设是一些处理程序错误地调用了
next
两次

一般来说,我会建议再次保护这一点,无论如何,你可以使用类似

function callNext(req, res, handlers, cb) {
   let lastCalledIndex;
   let next = (thisObj, index) => {
       if (index === lastCalledIndex) { 
           console.log("'next' called multiple times from handler");
           return; 
       }
       lastCalledIndex = index;
       if (i === handlers.length) {
           return cb();
       } else if (index > handlers.length) {
           console.log("'index' should not be higher than handlers.length.");
           console.log(handlers.length, index); // => 9 10
           return;
       }

       try {
           return handlers[index].call(thisObj || this, req, res, next.bind(undefined, thisObj, index + 1));
       } catch (e) {
           this.onerror(e, req, res);
       }
    };

    return next(this, 0);
}

如果
handlers.length
始终为空,则大于1的数字大于null@AyonLee经过消毒,以确保他们不会调用
next
两次?感谢您的启发,这很有帮助。
function callNext(req, res, handlers, cb) {
   let lastCalledIndex;
   let next = (thisObj, index) => {
       if (index === lastCalledIndex) { 
           console.log("'next' called multiple times from handler");
           return; 
       }
       lastCalledIndex = index;
       if (i === handlers.length) {
           return cb();
       } else if (index > handlers.length) {
           console.log("'index' should not be higher than handlers.length.");
           console.log(handlers.length, index); // => 9 10
           return;
       }

       try {
           return handlers[index].call(thisObj || this, req, res, next.bind(undefined, thisObj, index + 1));
       } catch (e) {
           this.onerror(e, req, res);
       }
    };

    return next(this, 0);
}