首页 > 解决方案 > 处理完所有文件后,我最后得到未定义错误的 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);


    }

标签: angulartypescript

解决方案


也许之后:

if(numberOfFiles === 0) {
   clearInterval(repeat);
   return; // <-- stop further processing
}

推荐阅读