Node.js的同步代码与异步代码

Node.js的同步代码与异步代码

问题描述:

我们正在使用node,主要用于内部项目并了解使用该技术的最佳方式。

We are working with node, mainly for an internal project and to understand the best way to use the technology.

不是来自特定的异步背景,学习曲线可能是一个挑战,但我们已经习惯了框架并学习了这个过程。

Not coming from a specific asynchronous background the learning curve can be a challenge but we are getting used to the framework and learning the process.

使我们两极化的一件事是,使用同步代码与异步代码的最佳时间是。我们当前正在使用规则,如果有任何事情与IO交互,那么它必须通过回调或事件发射器(即给定的)是异步的,但是其他不以任何方式使用IO的项可以构造为同步函数(这还取决于函数本身的重量以及它实际上是如何阻塞的)但这是使用Node.js时最好的方法吗?

One thing that has polarised us is when the best time to use synchronous code vs asynchronous code is. We are currently using the rule that if anything interacts with IO then it has to be asynchronous via call backs or the event emitter (thats a given), but other items which are not in any way using IO can be constructed as synchronous functions (this will depends as well on the heaviness of the function itself and how blocking it actually is) but is this the best approach to take when working with Node.js?

例如,我们正在创建一个Hal + JSON构建器,它现在存在于我们的代码库中。它是同步的,因为它所做的只是创建一些相当小的对象文字,仅此而已,没有外部依赖,当然也没有IO交互。

For instance, we are creating a Hal+JSON builder, which currently exists within our code base. It is synchronous simply because all it is doing is creating some rather smallish object literals and nothing more, there are no external dependencies and certainly no IO interactions.

我们的方法是否合适?

假设你有两个函数, foo bar ,它们是同步执行的:

Let's say you have two functions, foo and bar, which are executing synchronously:

function foo() {
    var returnValue = bar();
    console.log(returnValue);
}

function bar() {
    return "bar";
}

为了使API异步,将其更改为使用回调:

In order to make the API "asynchronous" is to change it to use callbacks:

function foo() {
    bar(function(returnValue) {
        console.log(returnValue);
    });
}

function bar(callback) {
    callback("bar");
}

但事实是,这段代码仍然是完全同步的。回调正在同一个调用堆栈上执行,并且没有进行线程优化,也没有可伸缩性的好处。

But the fact of the matter is, this code is still entirely synchronous. The callback is being executed on the same call stack, and no threading optimizations are being made, no scalability benefits are to be had.

然后它成为代码可读性的问题和编码风格。我个人发现典型的 var val = func(); 类型代码更易读,更容易理解。唯一的缺点是,如果你有一天需要更改 bar 的功能,那么它需要执行一些I / O活动或调用其他一些功能是异步的,您还需要更改 bar 的API。

It then becomes a question of code readablity and coding style. I personally find the typical var val = func(); type code more readable and readily understandable. The only drawback is, that if you one day would need to change the functionality of bar so, that it would need to perform some I/O activity or call some other function which is asynchronous, you need to change the API of baras well.

我的个人偏好:适用时使用传统的同步模式。当涉及I / O或有疑问时,始终使用异步样式。

My personal preference: use traditional, synchnous patterns when applicable. Always use asynchronous style when I/O is involved or when in doubt.