Reputation: 817
Hi I have several files that need to be read in a specific order.
To do this, I tried to implement file reads that spawned off the onloadend
function of the previous file.
My MWE is here: https://jsfiddle.net/q3h49dL2/
With the following test code:
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();
The general idea is that I queue a bunch of files and their filehandler task functions into linked queue.
Each queue then hooks the previous job in the queue into the runBeforeFunc
in Task.readFile
which executes before the current file is handled.
This does not seem to work however, and regardless of whether I move the runbeforeFunc
before or after the callback(text)
statement in the Task.readFile
function, it still executes the jobs in the wrong order.
What am I doing wrong?
Upvotes: 0
Views: 234
Reputation: 817
Solved it, trivial practically:
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);
}
}
Upvotes: 0
Reputation: 604
Maybe a bit trivial answer, but why don't you just change the order, like;
// Now queue them
this.addReadJob(job3);
this.addReadJob(job2);
this.addReadJob(job1);
https://jsfiddle.net/4Lv10zk1/
Upvotes: 1