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

人盡茶涼 提交于 2019-11-29 17:43:09

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.

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