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

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

问题描述

例如:

使用 jquery ajax 并行获取 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 个 promise 都得到解决,或者 5 个 promise 中的一个出现错误.它与 RSVP.alljQuery.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 这将允许您按顺序接收已解决的承诺.但是,我不清楚它们是否会并行启动,第二个 promise 应仅在第一个 promise 解决后才开始.

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),它应该并行运行两个 Promise,并且在任何时候它们只会是两个 Promise 被启动".

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天全站免登陆