并行触发异步请求,但使用rxjs按顺序获取结果 [英] Fire async request in parallel but get result in order using rxjs

查看:45
本文介绍了并行触发异步请求,但使用rxjs按顺序获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

使用jquery ajax在parrallel中获取5页.当page2返回时,什么也不做.当page1返回时,对page1和page2进行操作.

Get 5 pages in parrallel using jquery ajax. When page2 return, do nothing. When page1 return, do something with page1 and page2.

// assume there is some operator that can do this, 
// then it might look like this?
Rx.Observable.range(1, 5).
someOperator(function(page) {
  return Rx.Observable.defer( () => $.get(page) );
}).scan(function(preVal, curItem) {
  preVal.push(curItem);
  return preVal;
}, []);

推荐答案

存在 forkJoin 运算符,该运算符将并行运行所有可观察序列并收集其最后一个元素.(引自文档).但是,如果您使用那一个,则必须等待所有5个诺言得以解决,或者等待5个诺言之一出错.它非常接近 RSVP.all jQuery.when .因此,一旦您拥有第二个,那将不允许您做某事.无论如何,我都会提到它,以防在其他情况下对您有用.

There exists the forkJoin operator which will run all observable sequences in parallel and collect their last elements. (quoted from the documentation). But if you use that one, you will have to wait for all 5 promises to resolve, or one of the 5 to be in error. It is the close equivalent to RSVP.all or jQuery.when. So that would not allow you to do something once you have the second. I mention it anyways in case it might be useful to you in another case.

另一种可能性是使用 concatMap ,这将使您能够按顺序接收已解决的承诺.但是,我不清楚它们是否会同时启动,第二个承诺应该仅在第一个承诺解决后才开始.

Another possibility is to use concatMap which will allow you to receive the resolved promises in order. However, I don't have it clear that they will be launched in parallel, the second promise should start only when the first one has resolved.

我可以考虑的最后一个选择是使用 merge(2),它应同时运行两个诺言,并且在任何时候它们都将是启动"的两个诺言.

Last option I can think about is to use merge(2), that should run two promises in parallel, and at anytime they will only be two promises being 'launched'.

现在,如果您不使用 defer ,而使用 concatMap ,我相信您应该启动所有AJAX请求,并且顺序正确.所以你可以写:

Now if you don't use defer, and you use concatMap, I believe you should have all AJAX request started, and still the right ordering. So you could write :

.concatMap(function(page) {
  return $.get(page);
})

相关文档:

这篇关于并行触发异步请求,但使用rxjs按顺序获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆