angular - 处理完所有文件后,我最后得到未定义错误的 id
问题描述
简而言之,下面的代码应该获取在后端处理的当前正在运行的文件的进度。它做它应该做的一切。但是最后当所有文件都被处理时,这意味着当 this.currentlyRunning.length 的长度为 0 之后,我在此行的控制台“未定义索引”中收到错误
let file_id = {
userFileId: this.currentlyRunning[index].id
}
该代码一次又一次地调用 api 获取当前运行数组中的所有文件的进度,直到达到 100% 的进度。这就是我使用 setInterval 的原因。假设当前正在运行的列表中有两个文件,get progress 方法将在每 4000 毫秒后调用一次,并且每个文件的进度都会在视图中更新。处理完这两个文件后,控制台“未定义索引”上会抛出错误
checkProgress() {
let index = 0;
let repeat = setInterval(() => {
let numberOfFiles = this.currentlyRunning.length;
if(numberOfFiles === 0) {
clearInterval(repeat);
}
let file_id = {
userFileId: this.currentlyRunning[index].id
}
this.auth.getProgress(file_id).subscribe((res: any)=>{
this.currentlyRunning[index]['progress'] = Math.round(res.percent);
let indexOfFileHistory = this.uploadedFileHistory.findIndex((file: any)=> file.id === this.currentlyRunning[index].id);
this.uploadedFileHistory[indexOfFileHistory] = this.currentlyRunning[index];
if(this.currentlyRunning[index].progress === 100 || res.status == "badBounceRate") {
//the origial array which contains all the files we are just updating its status on 100% individual file object is returned with updated status
this.uploadedFileHistory[indexOfFileHistory] = res.data;
//removing the file from currently running
this.currentlyRunning.splice(index, 1);
}
//incrementing so that next time it runs for the other file
index = index + 1;
if(index >= numberOfFiles) {
index = 0;
}
let running = this.uploadedFileHistory.find((file: any)=>file.status === "Running");
if(!running) {
clearInterval(repeat);
}
},(err)=>{
//want to run it regardless of the error
index = index + 1;
if(index >= numberOfFiles) {
index = 0;
}
let running = this.uploadedFileHistory.find((file: any)=>file.status === "Running");
if(!running) {
clearInterval(repeat);
}
});
}, 4000);
}
解决方案
也许之后:
if(numberOfFiles === 0) {
clearInterval(repeat);
return; // <-- stop further processing
}
推荐阅读
- amazon-ec2 - Aws Auto Scaling 组终止了一个 ec2 实例,但实例状态检查失败
- ios - UIStackView排列子视图底部排列问题
- python - AWS Glue 作业:尝试将镶木地板文件写入 S3 时出现 SchemaColumnConvertNotSupportedException
- kubernetes - Helm 安装失败并显示“客户端未授权”
- asp.net-mvc - 从 Swagger 文档生成 HTML 页面
- c# - .net core-Logging 不适用于修改后的命名空间
- java - 验证完成后,EasyMock 在 tearDown 方法中验证对 mock 的调用
- grails-4 - 如何在 Grails 4 集成测试中注入服务器端口?
- react-native - 我需要将数据传递给场景并将我输入的内容显示到下一个屏幕
- angular - 查看销毁错误:尝试使用已销毁的视图:检测更改