Limited number of javascript promises is not working if running in infinite loop

泄露秘密 提交于 2019-12-18 09:47:44

问题


My idea is. I have limited number of workers. This workers must do some job. When worker done with job, then he must take other job, until complete all the jobs.

I write this code:

function createWorker(num){
  this.num = num;

  this.Run = (job) => (
    new Promise(
      (resolve, reject) => {
        setTimeout(() => { resolve({worker: this, num: this.num, job: job}); }, 5000);
      }
    )
  );
}

function Processing(maxWorkers, jobs){
  this.Workers = [];
  this.Jobs = jobs;

  this.Go = () => {
    return new Promise(
      (resolve, reject) => {
        while(true){
          let worker = this.Workers.pop();

          if (!worker) continue;

          let job = this.Jobs.pop();

          if (!job) break;

          worker.Run(job)
            .then(
              res => {
                console.log(res);
                this.Workers.push(res.worker);
              }
            );
        }

        resolve("Complete");
      }
    )
  }

  for(var i = 0; i < maxWorkers; i++){
    this.Workers.push(new createWorker(i));
  }
}

let jobs = ['a', 'b', 'c', 'd', 'e'];

let proc = new Processing(3, jobs);
proc.Go()
  .then(
    res => {
      console.log(res);
    }
  );

Code for one job is working well

let worker = new createWorker(1);
worker.Run("a")
  .then(
    res => {
      console.log("Complete " + res.num + " job " + res.job);
    }
  );

Why my code is not working? It looks like freezing.


回答1:


In javascript the event loop is only processed when there is no javascript code left to process. This is because javascript is single threaded. Therefore the event loop cannot be processed in parallel with javascript code. The basic structure of the interpreter is:

       execute javascript code ----------->  process event loop
                   ^                                 |
                   |                                 |
                   '---------------------------------'

In light of this, an infinite loop in javascript code means the event loop is never processed.

So what does this have to do with web workers? Well, web workers execute in their own thread therefore they will run in parallel with the infinite loop. However, the way we get data back from web workers is:

worker.Run(job).then()

And that requires the event loop to run. So while workers can run in parallel with an infinite loop no communications between the infinite loop and the worker will be processed because you're not letting the interpreter the chance to process the event loop.

You cannot use infinite loops in javascript apps.

What to do then?

The solution is to use the event loop. Use setTimeout() or setInterval() if you want periodic asynchronous looping. Or loop by "recursively" calling the function again inside .then() until you run out of things to process.



来源:https://stackoverflow.com/questions/44086784/limited-number-of-javascript-promises-is-not-working-if-running-in-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!