gpt4 book ai didi

javascript - js函数在条件满足时不返回

转载 作者:行者123 更新时间:2023-11-30 20:43:55 24 4
gpt4 key购买 nike

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

function callNext(req, res, handlers, cb) {
let i = -1;
let next = (thisObj) => {
i += 1;

if (i == handlers.length) {
return cb();
} else if (i > handlers.length) {
console.log("'i' should not be higher than handlers.length.");
console.log(handlers.length, i); // => 9 10
return;
}

try {
return handlers[i].call(thisObj || this, req, res, next);
} catch (e) {
this.onerror(e, req, res);
}
};

return next();
}

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

最佳答案

最简单的假设是某些处理程序错误地调用了 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);
}

关于javascript - js函数在条件满足时不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48940419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com