Utilizing Rxjs Observables to manage nested ajax requests can be done like the following example:
Rx.Observable.fromPromise($.getJSON('list1.json'))
.switchMap(function responseA(aResponse){
/* processing aResponse*/
if(aResponse.fileName){
return Rx.Observable.fromPromise($.getJSON(aResponse.fileName));
}
return Rx.Observable.fromPromise($.getJSON('list2.json'));
})
.subscribe(function(finalResponse){
/* processing finalResponse */
});
However, it is also possible to achieve the same result without using Observables and solely relying on promises:
$.getJSON('list1.json')
.then(function responseA(aResponse){
/* processing aResponse*/
if(aResponse.fileName){
return $.getJSON(aResponse.fileName);
}
return $.getJSON('list2.json');
})
.then(function(finalResponse){
/* processing finalResponse */
});
Both approaches work, but some may argue that utilizing promises leads to cleaner code. However, there is a belief that Rx Observable is more standard and efficient when handling asynchronous requests.
When considering code organization, convention, and performance in handling ajax requests, which option (promise or Observable) would be preferable?
If the preference is towards using Observable, then which operators (switchMap/MergeMap) would be recommended for these types of situations?