使用 RxJS Observables 的 Promise.all 行为?

新手上路,请多包涵

在 Angular 1.x 中,我有时需要发出多个 http 请求并对所有响应进行处理。我会将所有承诺放入数组中并调用 Promise.all(promises).then(function (results) {...})

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

原文由 Corey Ogburn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

使用 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!' ]

原文由 arcseldon 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题