在 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(...);