[英]Why is my for loop containing a fetch API call only running once?
我有一个循环来验证最多5个ids
如果它们确实存在)。 我有一个for循环,该循环遍历ids
,调用端点进行检查,并对结果进行某些功能。
我遇到的问题是循环只运行了一次,然后似乎从函数中退出了。 我的功能如下:
isValidAIN(ains) {
var control = this;
var length = ains.length;
//length is logging correctly when the function is called.
console.log("length: ", length);
if (length > 0) {
for (let i = 0; i < length; i++) {
//this runs once only
console.log("i: ", i);
if (ains[i].length !== 10) {
//this doesn't run
console.log("length: ", ains[i].length);
console.log("object in length: ", ains[i].length);
console.log(ains[i]);
if (ains[i].length === 0) {
this.state.errors["ain[" + i + "]"] = "";
this.state.validAINS[i] = true;
} else {
this.state.errors["ain[" + i + "]"] = "This AIN Number Must Contain 10 Digits";
this.state.validAINS[i] = false;
}
this.setState(this.state);
} else {
//this log only runs once
console.log("this should run for every iteration but only runs once");
fetch("/myendpoint/?ain=" + ains[i])
.then(res => res.json())
.then(
(result) => {
console.log("success: ", result);
if (result == null) {
//This logs to 0 for the first iteration and then does not repeat. I am purposely entering invalid ids to hit this area.
console.log("i: ", i);
control.state.errors["ain[" + i + "]"] = "AIN Is Invalid";
control.state.validAINS[i] = false;
control.setState(control.state);
} else {
//not hitting this area
console.log("res: ", result);
control.state.errors["ain[" + i + "]"] = "";
control.state.validAINS[i] = true;
control.setState(control.state);
}
},
(error) => {
//not hitting this area
console.log("error: ", error);
}
)
}
}
} else {
return false;
}
}
在逐行注释代码时,我终于意识到自己的错误。 validAINS
数组已初始化为空数组,但从未实际使用值进行初始化。 因此,api调用与该问题无关,但是尝试将空数组的索引设置为值会破坏循环。 在ComponentDidMount
函数中初始化数组可解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.