如果在无限循环中运行,则有限数量的JavaScript Promise无法正常工作 [英] Limited number of javascript promises is not working if running in infinite loop

查看:92
本文介绍了如果在无限循环中运行,则有限数量的JavaScript Promise无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的想法是。
我的工人数量有限。
该工人必须做一些工作。
当工人完成工作后,他必须再从事其他工作,直到完成所有工作。

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.

我写这段代码:

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.

推荐答案

在javascript中,仅当没有要处理的javascript代码时才处理事件循环。这是因为javascript是单线程的。因此,事件循环无法与javascript代码并行处理。解释器的基本结构是:

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
                   ^                                 |
                   |                                 |
                   '---------------------------------'

鉴于此,javascript代码中的无限循环意味着永远不会处理事件循环。

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

那与网络工作者有什么关系?嗯,网络工作者在自己的线程中执行,因此他们与无限循环并行运行。但是,我们从Web Worker中获取数据的方式是:

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.

您不能在javascript应用程序中使用无限循环。

解决方案是使用事件循环。如果要定期进行异步循环,请使用 setTimeout() setInterval()。或在 .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.

这篇关于如果在无限循环中运行,则有限数量的JavaScript Promise无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆