您好,我有几个文件需要按特定顺序读取。
为此,我尝试实现由前一个文件的 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();
总体思路是,我将一堆文件及其文件处理程序任务函数排队到链接队列中。
然后,每个队列将队列中的前一个作业挂接到 Task.readFile
中的 runBeforeFunc
中,该作业在处理当前文件之前执行。
但这似乎不起作用,无论我是否将 runbeforeFunc
移动到 Task.readFile 中的
函数,它仍然以错误的顺序执行作业。callback(text)
语句之前或之后
我做错了什么?
最佳答案
也许答案有点微不足道,但你为什么不改变一下顺序,比如;
// Now queue them
this.addReadJob(job3);
this.addReadJob(job2);
this.addReadJob(job1);
关于javascript - 按顺序处理文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39918522/