如何在Node.js中编写非阻塞代码? [英] How do I write non-blocking code in Node.js?

查看:104
本文介绍了如何在Node.js中编写非阻塞代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 I / O http://en.wikipedia.org/wiki/Node.jsrel =nofollow noreferrer> Node.js 非常容易。这就是整个库的设置。

I can write non-blocking I/O in Node.js very easily. It's what the entire library is set up for.

但是所做的任何计算都是阻塞的。任何通过事件发射器阻止的消息都会阻止。

But any computation done is blocking. Any message passing over event emitters are blocking.

例如,发射事件立即被解决,因此阻塞:

For example, emitting events are resolved immediately and are thus blocking:

var e = new process.EventEmitter;
e.on("foo", function() {
    console.log("event");
});
process.nextTick(function() {
    console.log("next tick");
});
setTimeout(function() {
    console.log("timeout");
}, 0);
e.emit("foo");

> event
> next tick
> timeout

除了在 nextTick 中包装电话外,如何使代码无阻塞?

Apart from wrapping calls in nextTick, how do I make code non-blocking?

我想尽可能少地在事件循环的每个周期进行计算,这样我就可以同时为多个客户端服务可能。

I want to do as little computation per cycle of the event loop as possible, so that I can serve as many clients simultaneously as possible.

如何以非阻塞方式编写代码?

How do I write my code in a non-blocking fashion?

当我有非阻塞代码,如何在多个进程中扩展?

And when I have non-blocking code, how do I scale that across multiple processes?

一个选项是等待WebWorker子进程API完成。

One option is waiting for the WebWorker sub-process API to be finished.

推荐答案

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.

如果使用<$ c $分步处理c> 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()<几天前将/ code>添加到v0.5。它简化了子进程的创建和通信 - 不仅仅是Web worker API,而是关闭,请参阅 URL
https://github.com/joyent /node/blob/master/doc/api/child_process.markdown

这篇关于如何在Node.js中编写非阻塞代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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