我正在用Rx.js练习一些方法。我写了一段代码来解决多个承诺。只是想知道我是以正确的方式做到还是有更好的方法(可能更短)?
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));
输出:来自github api的两个JSON对象。
答案 0 :(得分:2)
我可能会使用fromArray
+ flatMap
代替:
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);
});