Javascript 当条件满足时,js函数不返回
下面的代码,我找不出任何问题,但它有时会输出 “'i'不应大于handlers.length”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
将在之后的下一次调用中递增,如果(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);
}