使用 Javascript 进行响应式编程 [英] Reactive programming with Javascript

查看:66
本文介绍了使用 Javascript 进行响应式编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是响应式编程的新手,阅读所有这些我看不懂的文章时有点不知所措.

I m new in reactive programming and I m a bit lost reading all these articles that I can't understand.

实际上,我是一名来自 Nodejs、Angularjs、Angular 2 和 React 的 JavaScript 开发人员.

Actually, I m a javascript developer from Nodejs, Angularjs, Angular 2 and React.

我做什么

我一直使用 promises,用于远程数据获取、本地异步解析等......比回调更好的可测试性并满足我的需求.

I use promises all the time, for remote data fetching, local async resolution etc... Better testability than callbacks and fit my needs.

我对流的理解

除非在特定情况下,我不知道流可以在哪里拯救我.

I can't figure out where streams can save me except in a particular case.

这种特殊情况是我不能在监听流时使用承诺,因为承诺只会被解析一次.

This special case, is that I can't use promises while listening on streams because the promise would be resolved only once.

使用 SocketIo 的示例:

An example with SocketIo:

io.on('connection',  (socket) => {
  // this works
});

io.on('connection').then((socket) => {
  // this can't work, promise would be resolved only once
});

如果我没记错的话,我可以通过简单地返回一个 observable 来使用响应式流来管理这种情况.对吗?

If I m not wrong, I could use reactive streams to manage this case by simply returning an observable. Right ?

我不明白的地方

我正在学习 Angular 2 和所有相关的东西.实际上,从许多博客中可以看出,人们过去常常使用 observable 来获取远程数据,而我无法理解使用它代替 promise 有什么优势.

I m studying Angular 2 and all the stuff around. Actually, from many blogs, people use to use observables to fetch remote data and I can't understand what could be an advantage of using it instead of promises.

事实是,在这两种情况下我都需要制作一个遥控器,那么为什么一个比另一个多呢?这是性能问题吗?

The fact is that I would need to make a remote like in both cases, so why more one than the other ? Is this a performance issue ?

我需要什么

如果您已经阅读了整个问题,我需要了解在远程数据获取的情况下使用反应式编程而不是 Promise 的优势是什么?

If you've read the whole question, what I need is to understand what are the advantages of using reactive programming instead of promises in the case of remote data fetching ?

在哪些(其他情况下)使用反应式的东西比使用通常的东西更好?

In which (other cases) could it be better to use reactive stuff than usual stuff ?

推荐答案

@Günter 为您提供了 observables 的基础,尤其是 Promise 被调用的能力.

@Günter gave you the foundations of observables especially the ability of promises to be called.

更进一步,我认为 observables 的主要优势是能够使用运算符构建异步数据流/流.

To go a bit further, I think that the key advantage of observables is the ability to build an asynchronous data flow / stream using operators.

以下是一些具体的用例:

Here are some concrete use cases:

  • debounceTime/switchMap.当您想利用表单输入根据相应的 HTTP 请求过滤列表时,您需要为请求使用的值是用户完成写入时的值.没有必要发送多个请求:每个新字符一个(一个用于 's',一个用于 'so',一个用于 'som',......,一个用于 'something to search').debounceTime 运算符通过缓冲事件并在一段时间不活动后提供最后一个事件来实现这一点.

  • debounceTime / switchMap. When you want to leverage a form input to filter a list based on corresponding HTTP requests, the value you need to use for the request is the one when the user has finished to write. It's not necessary to send several requests: one per new characters (one for 's', one for 'so', one for 'som', ..., one for 'something to search'). The debounceTime operator allows this by buffering events and provides the last one after an amount of time of inactivity.

这是一个示例:

@Component({
  (...)
  template: `
    <input [ngFormControl]="ctrl"/>
  `
})
export class MyComponent {
  constructor() {
    this.ctrl = new Control();
    this.ctrl.valueChanges
               .debounceTime(500)
               .distinctUntilChanged()
               .switchMap((vallue: string) => {
                 // Get data according to the filled value
                 return this.service.getData(entry);
               })
               .subscribe(data => {
                 // Update the linked list
                 this.list = data;
               });
  }
}

如果您只使用 switchMap,则每个输入将有一个请求,但之前进行中的请求将被取消.这允许您获得正确的结果,尤其是在某些请求的请求执行时间较长的情况下.

If you only use switchMap, you will have one request per input but previous in-progress requests will be canceled. This allows you to get the correct result especially if request execution times is longer for some requests.

在这种情况下,您可以将来自 Web UI 的事件(DOM 事件)链接到 HTTP 请求以相应地执行(对事件做出反应)并应用一些高级行为.

In this case, you can link the event from the Web UI (DOM events) to HTTP requests to execute accordingly (react on events) and apply some advanced behaviors.

实现重试.通过混合使用 retryWhendelaytimeout 运算符,您可以轻松(且透明地)实现重试

Implement retry. By mixing retryWhen, delay and timeout operators, you can easily (and transparently) implement retries

searchPlaces(searchText:string) {
  var params = new URLSearchParams();
  params.set('placename_startsWith', searchText);
  params.set('username', 'templth');

  return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
      { search: params })
    .retryWhen(error => error.delay(500))
    .timeout(2000, return new Error('delay exceeded'))
    .map(res => res.json().postalCodes);
}

我认为这就是 observables 的真正力量:异步处理链/数据流和基于事件链接应用程序的不同部分.这是 Promise 无法完成的事情,它允许实现用例以使您的应用程序更健壮.

I think that this is the real power of observables: the asynchronous processing chain / data flow and linked different parts of the application based on events. It's something that can't be done with promises and allow to implement use cases to make your application more robust.

这里有一系列文章可以为您提供更多详细信息:

Here is a series of articles that could give you more details:

这篇关于使用 Javascript 进行响应式编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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