RxJS序列相当于promise.then()? [英] RxJS sequence equivalent to promise.then()?

查看:165
本文介绍了RxJS序列相当于promise.then()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去经常发展很多,现在我转向RxJS。 RxJS的文档没有提供关于如何从promise链转移到观察者序列的非常明确的例子。

I used to develop a lot with promise and now I am moving to RxJS. The doc of RxJS doesn't provide a very clear example on how to move from promise chain to observer sequence.

例如,我通常用多个步骤编写promise链,喜欢

For example, I usually write promise chain with multiple steps, like

// a function that returns a promise
getPromise()
.then(function(result) {
   // do something
})
.then(function(result) {
   // do something
})
.then(function(result) {
   // do something
})
.catch(function(err) {
    // handle error
});

我应该如何以RxJS风格重写此承诺链?

How should I rewrite this promise chain in the RxJS style?

推荐答案

对于数据流(相当于然后):

For data flow (equivalent to then):

Rx.Observable.fromPromise(...)
  .flatMap(function(result) {
   // do something
  })
  .flatMap(function(result) {
   // do something
  })
  .subscribe(function onNext(result) {
    // end of chain
  }, function onError(error) {
    // process the error
  });

可以使用 Rx.Observable.fromPromise

A promise can be converted into an observable with Rx.Observable.fromPromise.

一些承诺运营商有直接翻译。例如 RSVP.all jQuery.when 可以替换为 Rx.Observable。 forkJoin

Some promise operators have a direct translation. For instance RSVP.all, or jQuery.when can be replaced by Rx.Observable.forkJoin.

请记住,您有一堆允许异步转换数据的运算符,并执行您不能或不会执行的任务很难做到承诺。 Rxjs使用异步数据序列(序列即超过1个异步值)显示其所有功能。

Keep in mind that you have a bunch of operators that allows to transform data asynchronously, and to perform tasks that you cannot or would be very hard to do with promises. Rxjs reveals all its powers with asynchronous sequences of data (sequence i.e. more than 1 asynchronous value).

对于错误管理,主题稍微复杂一些。

For error management, the subject is a little bit more complex.


  • catch 终于运营商

  • retryWhen 也可以帮助重复序列出现错误

  • 您还可以使用 onError 函数处理订阅者本身的错误。

  • there are catch and finally operators too
  • retryWhen can also help to repeat a sequence in case of error
  • you can also deal with errors in the subscriber itself with the onError function.

要获得精确的语义,请深入了解您可以在网上找到的文档和示例,或在此处提出具体问题。

For precise semantics, have a deeper look at the documentation and examples you can find on the web, or ask specific questions here.

这绝对是使用Rxjs进行更深入错误管理的良好起点: https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html

This would definitely be a good starting point for going deeper in error management with Rxjs : https://xgrommx.github.io/rx-book/content/getting_started_with_rxjs/creating_and_querying_observable_sequences/error_handling.html

这篇关于RxJS序列相当于promise.then()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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