How do I write non-blocking code in Node.js?

我与影子孤独终老i 提交于 2019-11-30 03:11:56
Ricardo Tomasi

JavaScript is single-threaded. That means that regardless of events, timeouts, or delaying with nextTick, any computation done will block the whole process.

If you split your processing in steps using process.nextTick, like it's done with setTimeout(fn, 0) on the client-side to avoid blocking the UI, you could spread your workload over a longer time span, giving some room for other functions to run.

But that's a very innefective solution - the total amount of work is the same, distributed among all cycles (making each request a little slower). In practice, any kind of computation that is expected to take more than a few milliseconds should be offloaded to a different process. To maximize concurrency you should always return to the event loop as quickly as possible.

child_process.fork() was added to v0.5 a few days ago. It simplifies child process creation and communication - not quite the web workers API, but close, see the URL https://github.com/joyent/node/blob/master/doc/api/child_process.markdown.

There's no real multi-threading in JavaScript and that's what you need to make the call non-blocking. The only thing I can think of are web-workers: https://developer.mozilla.org/en/Using_web_workers

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