Home  >  Article  >  Web Front-end  >  Explore how to apply reactive programming in Node? Advantages and Disadvantages Analysis

Explore how to apply reactive programming in Node? Advantages and Disadvantages Analysis

青灯夜游
青灯夜游forward
2022-02-14 20:09:172033browse

This article will help you explore reactive programming with Node.js, and introduce how to apply reactive programming in Node, as well as its benefits, pros and cons. I hope it will be helpful to everyone!

Explore how to apply reactive programming in Node? Advantages and Disadvantages Analysis

Reactive programming provides advanced data flow, the ability to create and manipulate streams of events in a predictable manner.

This article will tell Node.jsdevelopers how to apply reactive programming in Node, as well as its benefits and disadvantages.

This article will cover the following content.

  • Fundamentals of Reactive Programming

  • Why consider reactive programming in Node.js?

  • When to use reactive programming methods

  • Benefits of reactive programming

  • Reactive Disadvantages of Programming

  • Introduction to coordination and its benefits/cons

  • Reactive programming library for Node

What is reactive programming?

In short, a program is said to be reactive when a change in input results in a corresponding change in output, without the need to manually update the change in output. This allows software engineers to bypass the stress of manually handling huge implementations.

The functional reactive programming paradigm makes our reactive code base easy to read and understand because it reduces callback hell, which makes asynchronous code blocks difficult to read.

Since reactive programming has a lot to do with asynchronous operations, a functional approach makes it easier for us to determine the results of asynchronous operations.

Basic Principles of Reactive Programming

Operators

Operators are methods that Observables heavily rely on. They have the following usage scenarios.

  • Convert asynchronous events to Observables when handling asynchronous requests
  • Combining a sequence of multiple observable variables into a single observable variable
  • Error Handling
  • Handling time-based operations

Observable operators include[filter(...)](https://rxjs.dev/api/operators/ filter),[mergeMap(...)](https://rxjs.dev/api/operators/mergeMap),[of](https://rxjs.dev /api/index/function/of),[from](https://rxjs.dev/api/index/function/from),[concat](https:/ /rxjs.dev/api/index/function/concat) method, etc.

Observable Stream

An Observablestream is an array of multiple input values ​​that are processed over time. An Observable emits events to its subscribers, who in turn listen to these events for further processing. Observable streams can be combined to create new streams. Array methods, such as map, reduce, filter, etc., are used to operate streams.

Values ​​can be emitted to subscribers as follows.

import { of, Observable } from "rxjs"; 
const emitter : Observable<string> = of("Sam", "Ray", "Thomas");

Subscribers

Observable subscribers are more like array iterators. They loop through the resulting Observable streams, making it possible to transform or process each stream.

The following snippet shows how to subscribe to an Observable stream.

emitter.subscribe((value: string) => {
  console.log(`Name: ${value}`)
})

Reactive programming has some built-in subscription methods, such as emit and flatMap map methods. These methods allow us to listen to each value of the Observable stream and update it accordingly. Our need is to process them.

Standards for reactive systems

A fully reactive Node.js system should meet the following standards.

Responsive architecture

A reactive system should have a good user experience and provide timely response to user interactions.

Resilient Architecture

Resilient architecture, if implemented correctly, will allow the system to respond to errors without disrupting the entire system.

This architecture ensures that each node has a replica. If the master node fails, there is some kind of fallback on the other available nodes.

Scalability

The system should be able to handle different loads related to its ability to scale down when the infrastructure requires few or no resources Scale, and when the infrastructure requires more resources, it can be scaled up to provide an effective cost management strategy.

In addition, the system should also be able to handle point-in-time loads.

Why should you consider reactive programming with Node.js?

Now that we have briefly discussed the fundamentals of reactive programming, it is also important to understand the reasons to consider a reactive approach to programming with Node.js.

Scalability

Writing functional reactive code makes it easier to manage the code base and improves the scalability of the project.

功能实现

对于需要定期修改功能或增加新功能的项目来说,编写功能性反应式代码使得新功能更容易被添加到现有项目中。

与时间相关的错综复杂的问题

在对外部API进行异步请求时,我们确实会遇到一些时间限制的约束。这些限制可以用反应式编程方法有效地处理。

减少代码的冗长性

实施反应式编程范式将极大地减少实现特定功能所需的代码量。

引入协调和它的好处/权衡

在反应式编程诞生之前,用Node.js构建微服务需要协调所有服务互动的协调器模式。

协调器模式的一个典型用例是在电子商务应用中拥有微服务,这些微服务按顺序处理以下任务:从购物车中获取客户订单,计算总金额,生成账单,在成功付款后,更新产品库存并创建一个订单ID,并向卖家提供Pending

虽然这提供了一个系统的方法来处理应用程序的逻辑流程,但依赖关系紧密耦合的一个主要缺点会破坏整个系统。例如,如果前面的服务出现故障,那么所有的依赖服务都不会被执行。

在Node.js中何时使用反应式编程方法

反应式编程不是一个万能的方法,但它在一些特定的情况下是非常合适的。

  • 当需要将应用流分散到可管理的微服务中时,反应式编程模式是非常合适的。
  • 当需要在有限的时间内将应用交付给生产时
  • 当前面的一个依赖性的临时关闭会导致整个系统的崩溃时
  • 当有很多异步的代码块,而等待的结果可能被延迟时,反应式编程也是非常合适的。

Node.js中的反应式编程的弊端

虽然功能化的反应式编程方法减少了协调器模式遇到的缺点,但它不能取代协调器模式,因为它有自己的缺点。

  • 分解应用流程并分布在所有服务中所产生的冗余代码块
  • 为了构建反应式服务,需要对流和事件循环有一个全面的了解

Node.js中流行的反应式编程库

RxJS

这是JavaScript中最流行的反应式编程库之一,被积极维护。

在写这篇文章的时候,RxJS正在从v7过渡到v8,它在上周有超过2700万次的下载。这次过渡的特点是重写了库的性能,更好的模块化,更好的可调试的调用堆栈,以及向后的兼容性。

下面是一个快速的RxJS使用例子。

import { range } from "rxjs";
import { map, filter } from "rxjs/operators";

range(1, 200)
  .pipe(
    filter(result => result % 2 === 1),
    map(result => result * 2 )
  )
  .subscribe(result => console.log(result));

Reactor.js

Reactor.js是另一个用于反应式编程的JavaScript库。虽然与Bacon.js和Rxjs相比,它还不是很流行,但它以轻量而闻名。使用Reactor.js在复杂的数据模型中保持一致性要容易得多,因为它能自动跟踪反应式变量,并在任何反应式变量的值发生变化时重新触发观察者。
使用Reactor.js,不需要手动设置订阅/监听器,因为依赖关系会自动为你设置。

下面是一个Reactor.js使用的快速例子。

const reactor = new Reactor({ name: "Doe" });

observe(() => {
  console.log("My name is ", reactor.name);
}); // prints "My name is Doe"

reactor.name = "John "; // prints "My name is John"

Reactor是基于与Bacon.jsKnockout.js相同的反应式原理。

其他用于反应式编程的JavaScript库包括。

  • Flyd
  • Bacon.js
  • Knockout.js
  • Kefir
  • 大多数

总结

在这篇文章中,我们探讨了反应式编程,它的好处,以及何时最适合我们的Node.js项目。此外,我们还讨论了协调、其好处/利弊以及用于Node.js中反应式编程的JavaScript库。

希望你能发现这篇文章的信息量和帮助。

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Explore how to apply reactive programming in Node? Advantages and Disadvantages Analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete