简体   繁体   中英

Resolving Multiple Promises With Rx.js, is there a better way?

Well i was practicing some methods with Rx.js . I've written a piece of code to resolve multiple promises. Just wanted to know whether i'm doing it the right way or is there any better way of doing it (maybe shorter) ?

var urls = ["https://api.github.com/users/manju4ever","https://api.github.com/users"];
var responseList = Rx.Observable
                 .merge(urls.map(eachUrl => 
                                 Rx.Observable.fromPromise($.getJSON(eachUrl))));

responseList.subscribe(response => console.log(response));

Output: Two JSON Objects from github api.

I would probably use fromArray + flatMap instead:

var urls = ["https://api.github.com/users/manju4ever","https://api.github.com/users"];

var responses = Rx.Observable.fromArray(urls)
             //Implicitly handle the promises
             .flatMap(function(url) {
               return $.getJSON(url);
             });

responses.subscribe(function(res) {
  console.log(res);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM