Navigating through ajax query - Weighing the pros and cons between Promises and RxJs observables

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?

Answer №1

Is there something I'm overlooking here because I've heard that Rx Observable is considered more standard and efficient for managing asynchronous requests?

No, you're not missing anything. While Rx is indeed valuable, in this specific scenario, code based on promises may be simpler.

Generally speaking, if you only require a single value - opt for a promise. If you need to handle multiple values going in and out, then observables (or the future async iterators) would be better suited.

Rx becomes beneficial when you want to easily implement:

  • Retrying failed requests (using Observable.defer).
  • Focusing solely on the last request made.
  • Incorporating built-in cancellation functionality.

It's important to note that promises can also achieve these functionalities with the use of libraries. These characteristics are not exclusive to observables.

Rx truly excels when dealing with input beyond a singular call. For instance, if you need to trigger these calls every time the user clicks something, ignore clicks under certain conditions, introduce a 100ms debounce delay, and only pay attention to the final call outcome - Rx comes in handy.

In this case at hand, promises are adequate and straightforward. Further simplification of your promise-based code could look like this:

$.getJSON('list1.json').then(x => $.getJSON(x.fileName || 'list2.json'))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a jQuery plugin called FullCalendar, dynamically create and set events using a

Using the jQuery full calendar, I am looking to dynamically set events. Here are some examples of events I need to set: events: [ { title: 'Long Event', start: '2016-09-07', ...

Using JavaScript object variables to populate an HTML button

Objective: I am attempting to populate the variables of a function inside the 'onclick' attribute of a dynamically created button using JavaScript and HTML. When the button is clicked, I want the function to execute based on the variables contai ...

Struggling to incorporate jquery and jquery-ujs into Browserify, encountering an error stating Uncaught ReferenceError: jQuery is not defined

I am currently working on a Ruby on Rails project and utilizing Browserify to manage my JavaScript dependencies. However, I keep encountering an error message stating "Uncaught ReferenceError: jQuery is not defined" because jquery-ujs is attempting to call ...

Is there a way to ensure the functionality of this code without exposing my API keys? I am currently developing an application using Node.js, Angular, and Express

I have come across an issue with my code where process.env is not working within a specific function. I need to find a way to call process.env without displaying my keys. If I don't add my keys, the API call won't function properly. What options ...

Having trouble parsing a JSON string in your JavaScript code?

As a java developer transitioning to JavaScript, I'm faced with the task of parsing a JSON string retrieved from a WebService. Here is the JSON String: { "myArrayList": [ { "myHashMap": { "firstName": "Clara", ...

Having trouble creating an angularjs table using ng-repeat in the controller?

I have a sample snippet that I would like to discuss. My goal is to display a JSON object in an angular table using ng-repeat, which is being generated from my angular controller script. I have attempted the code below, but for some reason, the table is no ...

Tips on setting a value to zero in Angular when there is no input

Is there a way to organize the data and show the PRN entries based on the date, for instance, when the month is January? If there is data for machine 1 with assetCode: PRN, it should be displayed under the header for children. Similarly, if there is data f ...

When calling the MVC Controller method, certain JSON fields are appearing as NULL

Upon making an ajax call, I have verified in the request header that all JSON fields contain values. However, when I debug on the server side, only the DateEntered field is populated (parsed into a DateTime object). Interestingly, when I input the same det ...

Angular.js repeatedly requesting data without ever successfully loading it

I'm currently learning Angular.js and have set up a Node app to serve a basic Angular web page with log data being written to stdout. Everything was running smoothly until recently when, for unknown reasons, the page started crashing every time I trie ...

Each time the button is clicked, the settings and values will rotate, creating a new

I'm looking to create a button system that transitions from "unmarked" to "form" and updates the database with each click. I want users to be able to cycle through the buttons, triggering a post request via ajax to update the associated ID in the data ...

Is the "Apply with LinkedIN" button not displaying correctly on the page?

I have managed to integrate the Apply with LinkedIN button on my website, but I am encountering a styling issue. The button is displaying strangely, even though I am using bootstrap 3.1. Has anyone else faced a similar problem and found a solution? I have ...

JQuery UI Tabs not responding to button clicks to switch tabs

I am experiencing an issue with a button in the first tab of my web page that has JQuery tabs with iFrames loaded in tabs 2 through 4. I want the button, when clicked, to switch to the next tab. EDIT 1: A Fiddle example showcasing the problem can be found ...

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

Error: Promise did not complete within the expected 2000ms timeframe, causing the test to timeout

Encountering an error message stating Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. It seems logical to ensure that a promise resolves when returning one, however, I be ...

Is it possible to convert an Object's property into a String resembling "Object.property"?

I am attempting to create a custom function that can convert the keys of an object I am accessing into a string representation. Here is an example: const test = { propertyOne: { propertyTwo: 0 }, propertyThree: { propertyFour: 0 } } functi ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Ensure that the placeholder text does not contain any null or empty values

I'm currently working with a dust.js template that generates input fields based on data received from the server. The issue I'm facing is that even when the data is empty, an input box with an empty placeholder value still gets rendered. Is there ...

Limiting the data obtained from the API to extract only the desired values

Using an API, I am retrieving customer information and displaying it in the console. The code snippet used for this operation is: if (this.readyState === 4) { console.log('Body:', this.responseText); } }; This returns a JSON object with v ...

Issue in the code causes a 500 error in admin-ajax.php

Recently, I noticed a change in how WordPress handles errors when writing functions for ajax calls on the front end. In the past, if there was an error in my code, I would easily see it in the Network tab of the Chrome inspector under my admin-ajax.php cal ...

Show an error message in Validation Summary through the use of Ajax

Solution: In order to display errors related to input without refreshing the webpage, utilize ValidationSummary with ajax functionality. Issue Encountered: Despite my efforts, I am facing challenges in implementing this approach effectively. Assistan ...