Observable - transforming two promises into an observable stream

I am facing a common scenario where I am looking to chain two promises together in such a way that if the first promise fails, the second promise needs to be canceled. In the world of 'Promises', the code would look something like this:

Fn1.doPromise( initialData )
  .then(info => {
        Fn2.doPromise( info )
              .then(result => {
                  //success - return result
              })
              .catch(error => {
                //error
              });
  })
.catch(error => {
  //cancel 2nd promise and show error
});

Now, I am investigating the best approach to achieve this using Observables, possibly with a library like RxJS. I would appreciate any insights or solutions shared. Thank you in advance!

Answer №1

When it comes to handling errors in RxJS, the approach is discussed thoroughly here. The key points include:

  • Catching Errors (using the catch operator either at the instance or class level)
  • Ignoring Errors with onErrorResumeNext
  • Retrying Sequences (using retry)
  • Ensuring Cleanup (with finally)
  • Ensuring Resource Disposal (using finally or using)
  • Delaying Errors (via mergeDelayError)

If you have a specific question, you can utilize Rx.Observable.fromPromise to convert a promise into an observable; and Rx.Observable.prototype.catch to handle errors as they arise.

Rx.Observable.fromPromise(Fn1.doPromise( initialData ))
  .flatMap(info => {
        return Rx.Observable.fromPromise(Fn2.doPromise( info ))
              .flatMap(result => {
                  //success - return result
                  // !! Make sure to return an observable or a promise here !!
              })
              .catch(error => {
                //error
                // !! Make sure to return an observable here !!
              });
  })
.catch(error => {
  //cancel 2nd promise and display error
  // !! Make sure to return an observable here !!
});

Here are some examples to further illustrate:

Answer №2

After conducting additional research, I managed to come across a versatile solution for chaining promises. This new method allows me to utilize as many promises as necessary in my code.

const executeAllPromises = (...funcs) => 
   funcs.reduce((acc, func) => 
   acc.flatMap(func), Rx.Observable.just())

executeAllPromises(promise1, promise2, promise3).subscribe();

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

Display or conceal a div depending on the selected radio button

I am attempting to display a hidden div based on the input of a radio button. If the "yes" option is checked, the hidden div should be shown. Conversely, if the "no" option is checked, the div should be hidden. I'm not sure why this code isn't w ...

How can jQuery Validate show validation messages specific to each field?

I need to validate numerous mandatory fields and display alert messages in a specific format: "Please fill in" followed by the field label. Currently, I am manually implementing this validation method as shown below: $("#myform").validate({ rules: { ...

What steps can I take to completely remove JavaScript from an HTML document?

To eliminate the <script> tags in the HTML, I can utilize regex just like this $html = preg_replace('#<script(.*?)>(.*?)</script>#is','', $html); While this approach works well, dealing with inline JavaScript require ...

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

napi and SWIG: ThreadSafeFunction only runs in a thread after the thread has finished its execution

Check out this repository I created, where a thread-safe function in a SWIG C++ class is executed using node-addon-api. The thread within the SWIG C++ class is triggered using the napi BlockingCallback as shown below: // C++ thread implementation for (int ...

What is the best way to create a function that can disable console.log and be imported into other React files for easy access?

Here is the content of my static.js file: var Helper = { console.log: function(){ }, Login: function(){ var name; var password; //rest of the code } } module.exports = Helper; Now, in my test.js file: var Helper ...

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

What is the reason behind why create-react-app generates the App.js file as a functional component?

Learning React has been quite fascinating for me. I recently used npx create-react-app my-project and noticed that the App.js file was created as a functional component, instead of a class component like in previous versions. After digging around, I stumbl ...

Problem with image title in jQuery mobile

My code seems to be having an issue where the title does not display completely when hovering over it. For example, if the title is set as "The Value", only "The" is shown and not "The Value". Can anyone help me identify the mistake? Thank you in advance ...

What is the best method for deleting the div with id "__next" in Next.js?

I'm currently working on a website using Next.js and I'm aiming to create a header with a position: sticky; effect. Nevertheless, Next.js automatically inserts a div with the attribute id="__next" at the top of my website without my co ...

Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false. To demonstrate this, I have created a fiddle below. ...

Is it necessary to re-export a module after modifying an attribute in it in JS/ES6?

From my understanding of the module system, when I use import 'some_module' in a file, I will always receive the same instance of that module and not a new instance each time. However, I am a bit puzzled by a pattern I have observed in certain a ...

Converting JSON formatting from Object to Array: A Comprehensive Guide

Encountering another issue with changing the JSON array output. Struggling to figure out why it's not rendering the other files. Providing a clearer explanation below: In my code snippet, when I use data[name] = {, each return name is rendered into ...

Ways to reset input fields following form submission

I've been trying to figure out how to clear the input fields once the form is submitted, but for some reason, the input data remains there even after each submission. I'm using ajax jquery form. Any ideas on how to resolve this issue? Thank you ...

Creating beautiful prints with images

I have been tasked with developing an MVC C# application where the contents of a div are dynamically created using an AJAX call to fetch data from a database. Upon successful retrieval, the content is then displayed as a success message in JavaScript. Here ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

Steps for importing a JavaScript file from Landkit into a Vue project

Currently, I am working on an interesting project and utilizing Vue with Landkit Bootstrap. However, I am encountering issues with the JavaScript behavior of the Landkit component. I usually import the following links in my index.html file, but in the new ...

Guide to implementing a delay in JavaScript/jQuery code right after invoking an asynchronous function

Is there a way to execute an asynchronous function and then introduce a delay in the subsequent code execution to ensure that the asynchronous operation has completed? I want to avoid wrapping the following code in a function and delaying it, I simply ne ...

Encounter a 401 error code while attempting to fetch data from CouchDB using an AJAX request

I attempted to make an AJAX call in a JavaScript file to fetch data from CouchDB. Unfortunately, I encountered a 401 error message: Failed to load resource: the server responded with a status of 401 (Unauthorized) This is an extract of my JavaScript cod ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...