Fire Async Request In Parallel But Get Result In Order Using Rxjs
For example:
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;
}, []);
Answer
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.
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.
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'.
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);
})
Relevant documentation:
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM