2019年5月的更新,使用RxJs v6
我发现其他答案很有用,并希望为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);
});
let source$ = zip(the_weather, the_tweets);
source$.subscribe(([weatherInfo, tweetInfo]) =>
console.log(weatherInfo, tweetInfo)
);
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!' ]