簡體   English   中英

順序處理文件內容

[英]Process file contents sequentially

嗨,我有幾個文件需要按照特定的順序讀取。

為此,我嘗試實現從前一個文件的onloadend函數產生的文件讀取。

我的MWE在這里: https : //jsfiddle.net/q3h49dL2/

使用以下測試代碼:

class Chain {
  // File Chain ops
  addReadJob(job) {
    console.log("Queuing:", job.file.name);

    if (this.firstjob === undefined) {
      this.firstjob = 0;
    }

    // Store previous job 
    var lastjob = this.firstjob;

    // Create new job that passes the previous job
    // as a readbeforefunc argument to new job.
    this.firstjob = function() {
      Task.readFile(job.file, job.task, lastjob);
    }
  }

  constructor() {
    //Let's create a bunch of jobs
    var job1 = {
      file: {name: "File1",text: "File1 contents"},
      task: Task.taskDoer1
    };
    var job2 = {
      file: {name: "File2",text: "File2 contents"},
      task: Task.taskDoer2
    };
    var job3 = {
      file: {name: "File3",text: "File3 contents"},
      task: Task.taskDoer1
    };

    // Now queue them
    this.addReadJob(job1);
    this.addReadJob(job2);
    this.addReadJob(job3);

    // And process them all from the first chain
    this.firstjob();
  }
}


class Task {
  static taskDoer1(text) {console.log("randomtask:", text);}
  static taskDoer2(text) {console.log("anotherrandomtask", text);}

  // !!!HERE PROBLEMS OCCUR!!!
  static readFile(file, callback, runbeforefunc = 0) {
    var fr = new FileReadPretend();

    fr.onloadend = function(text) {
      // Run previous job in chain first
      if (runbeforefunc !== 0) {
          runbeforefunc();
      }
      callback(text);
    }
    fr.readAsText(file);
  }
}


class FileReadPretend {
  constructor(){
     this.onloadend = null;
  }
  readAsText(file) {  
    var that = this;

    setTimeout(function() {
      that.onloadend(file.text);
      console.log("--read", file.name);
    }, 1000);
  }
}


new Chain();

總體思路是,我將一堆文件及其文件處理程序任務功能排入鏈接隊列。

然后,每個隊列將隊列中的上一個作業掛接到runBeforeFunc中的Task.readFile ,該runBeforeFunc在處理當前文件之前執行。

這似乎並不不過工作,也不管我移動runbeforeFunc前或后callback(text)在聲明中Task.readFile功能,它仍然以錯誤的順序執行的作業。

我究竟做錯了什么?

也許有點瑣碎的答案,但是為什么不改變順序呢?

 // Now queue them
    this.addReadJob(job3);
    this.addReadJob(job2);
    this.addReadJob(job1);

https://jsfiddle.net/4Lv10zk1/

解決這個問題,實際上很簡單:

addReadJob(job) {
   console.log("Queuing:", job.file.name);

   if (this.firstjob === undefined) {
       this.firstjob = function(){}; // dummy func
   }

   // Store previous job 
   var lastjob = this.firstjob;

   // Create new job that passes the previous job
   this.firstjob = function() {
        lastjob(); // <--- run lastjob first, duh!
        Task.readFile(job.file, job.task);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM