使用RxJS Observables的Promise.all行为? [英] Promise.all behavior with RxJS Observables?

查看:964
本文介绍了使用RxJS Observables的Promise.all行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 1.x中,我有时需要发出多个 http 请求,并对所有响应执行某些操作。我会把所有的promises抛出一个数组并调用 Promise.all(promises).then(function(results){...})

In Angular 1.x I would sometimes need to make multiple http requests and do something with all the responses. I would throw all the promises in an array and call Promise.all(promises).then(function (results) {...}).

Angular 2最佳实践似乎指向使用RxJS的 Observable 替代 http中的承诺请求。如果我有两个或更多从http请求创建的不同Observable,它们是否相当于 Promise.all()

Angular 2 best practices seem to point towards the use of RxJS's Observable as a replacement to promises in http requests. If I have two or more different Observables created from http requests, is their an equivalent to Promise.all()?

推荐答案

模拟 Promise.all 的更直接的替代方法是使用 forkJoin operator(它并行启动所有observable并加入它们的最后一个元素):

The more straightforward alternative for emulating Promise.all is to use the forkJoin operator (it starts all observables in parallel and join their last elements):

  • documentation
  • related link: Cf. RxJS: concat three promises, distinguish results

有点超出范围,但如果有帮助,关于链接承诺的主题,你可以使用一个简单的 flatMap :参见 RxJS承诺撰写(传递数据)

A bit out of scope, but in case it helps, on the subject of chaining promises, you can use a simple flatMap : Cf. RxJS Promise Composition (passing data)

这篇关于使用RxJS Observables的Promise.all行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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