Promise.all behavior with RxJS Observables?

后端 未结 4 1920
暖寄归人
暖寄归人 2020-11-27 17:12

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 cal

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 17:38

    Update May 2019 using RxJs v6

    Found the other answers useful, and wished to offer an example for the answer offered by Arnaud about zip usage.

    Here is a snippet showing the equivalence between Promise.all and the rxjs zip (note also, in rxjs6 how zip now gets imported using "rxjs" & not as an operator).

    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);
    });
    

    The output from both are the same. Running the above gives:

    { 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!' ]
    

提交回复
热议问题