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

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

问题描述

我曾经用 promise 进行过很多开发,现在我正在转向 RxJS.RxJS 的文档并没有提供一个非常清晰的例子来说明如何从承诺链转移到观察者序列.

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?

推荐答案

对于数据流(相当于then):

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
  });

promise 可以转换为 observable 使用 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.

请记住,您有一堆运算符可以异步转换数据,并可以执行使用 Promise 无法或很难完成的任务.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.

  • catchfinally 操作符
  • 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天全站免登陆