且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Node.js中编写非阻塞代码?

更新时间:2022-05-31 05:41:20

JavaScript是单线程的。这意味着无论事件,超时或延迟使用nextTick,任何完成的计算都将阻止整个过程。

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

如果使用 process.nextTick ,就像它在客户端使用 setTimeout(fn,0)一样,以避免阻止UI,你可以传播你的工作量在较长的时间跨度内,为其他功能提供了一些空间。

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()添加到v0.5。它简化了子进程的创建和通信 - 不仅仅是Web worker API,而是关闭,请参阅 URL
https://github.com/joyent /node/blob/master/doc/api/child_process.markdown