Tuesday 23 May 2017

Interrupt a function to do other stuff

The setup is a node js server

I am building a job handler i.e. It picks up jobs from a mongo db document and processes it and reports about the progress and also lets me stop the job midway(also saving its current state).

For testing purposes, I have a big data set of 1,000,000 numbers in an array and I am operating on that. I recently learned that JS is sequential at a functional level i.e. a function will run sequentially and nothing can interrupt it.

But that is a problem for me because I want to interrupt the function to receive other requests on my server(which I am not able to do currently) one of which will also help me send a stop request for the job.

Recently I learned about generator iterators, but even that does not work

function* hello(job, i) {


for(i; i<job.data.numbersToPrint.length; i++){
    if (runningJobs[job._id]) {
      console.log(job.data.numbersToPrint[i]);
      yield;
    } else {
      job.updateCurrentAndStop(currentJobStatus[job._id]);
    }
  }
}

let testJobHandler = function (job) {
  let i;
  if (job.currentlyProcessing !== null && job.currentlyProcessing.currentIndex)
    i = job.currentlyProcessing.currentIndex;
  else
    i = 0;
  currentJobStatus[job._id] = {};
  let gen = hello(job, i++);
  while(!gen.next(job, i).done) {
    console.log("NEXT");
    currentJobStatus[job._id].currentIndex = i;
    i++;
  }
};

which I suspected it won't because it will just pass the scope to another function.

Can anyone tell me how to interrupt a function efficiently and if that is not possible what else can I do to implement this feature.



via akabhirav

No comments:

Post a Comment