Promise.all behavior with RxJS Observables?
Promise.all behavior with RxJS Observables?
在 Angular 1.x 中,我有时需要发出多个http
请求并对所有响应执行一些操作。我会将所有承诺放在一个数组中并调用Promise.all(promises).then(function (results) {...})
.
Angular 2 最佳实践似乎指向使用 RxJS 的 Observable
作为http
请求中承诺的替代品。如果我从 http 请求创建了两个或多个不同的可观察量,是否有等效于 Promise.all()
?
模拟Promise.all
更直接的替代方法是使用 forkJoin
运算符(它并行启动所有可观察量并连接它们的最后一个元素):
- 文档
- 相关链接: 参考RxJS:结合三个承诺,区分结果
有点超出范围,但如果有帮助,在链接承诺的主题上,您可以使用一个简单的flatMap
: 参见 RxJS 承诺组合(传递数据)
> 使用 RxJs v6 更新 2019 年 5 月
发现其他答案很有用,并希望为Arnaud提供的关于zip
用法的答案提供一个例子。
这里有一个片段显示了Promise.all
和rxjs zip
之间的等价性(另请注意,在rxjs6中,zip现在如何使用"rxjs"而不是作为运算符导入)。
import { zip } from "rxjs";
const the_weather = new Promise(resolve => {
setTimeout(() => {
resolve({ temp: 29, conditions: "Sunny with Clouds" });
}, 2000);
});
const the_tweets = new Promise(resolve => {
setTimeout(() => {
resolve(["I like cake", "BBQ is good too!"]);
}, 500);
});
// Using RxJs
let source$ = zip(the_weather, the_tweets);
source$.subscribe(([weatherInfo, tweetInfo]) =>
console.log(weatherInfo, tweetInfo)
);
// Using ES6 Promises
Promise.all([the_weather, the_tweets]).then(responses => {
const [weatherInfo, tweetInfo] = responses;
console.log(weatherInfo, tweetInfo);
});
两者的输出是相同的。运行上述操作可得到:
{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]
{ temp: 29, conditions: 'Sunny with Clouds' } [ 'I like cake', 'BBQ is good too!' ]
forkJoin 也可以正常工作,但我更喜欢 combineLate,因为您无需担心它会占用可观察量的最后一个值。这样,只要它们中的任何一个发出新值,您就可以获得更新(例如,您按间隔或其他方式获取)。
在 reactivex.io forkJoin实际上指向Zip,它为我完成了这项工作:
let subscription = Observable.zip(obs1, obs2, ...).subscribe(...);
相关文章:
- 您的平台不支持RxJS-Array.observe
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 在rxjs中巧妙的蒸汽可观察合并
- http/rxjs catch回调中的Angular 2重定向导致TypeError:无法读取属性'订阅'
- RxJS等待承诺解决
- 如何在RxJS 5中创建Hot Observable
- RxJS油门行为;立即获取第一个值
- 如何获取RxJS Subject或Observable的当前值
- 困在使用RxJS删除所有计数器应用程序中
- 使用RxJS模拟命令队列和撤消堆栈
- 如何仅在RxJs中可观察到的源发出的特定错误上重试
- RxJS:在循环中处理错误.js自定义驱动程序
- 最后,在 rxjs 序列上,在第一个错误时执行
- RXJS 为什么只有最后一个数字同时有 a 和 b
- 使用rxjs创建一个可观察的对象,该对象稍后将连接到web套接字
- 正在寻找在rxjs中使用scan的更干净的方法
- 如何使用RXJS动态链接函数调用
- KnockoutJS添加和循环Observables
- 重新连接具有共享RxJS observable的WebSocket
- Promise.all behavior with RxJS Observables?