What is a suitable alternative to forkJoin for executing parallel requests that can still complete even if one of them fails?

Is there a more robust method than forkJoin to run multiple requests in parallel and handle failed subscriptions without cancelling the rest? I need a solution that allows all requests to complete even if one fails. Here's a scenario:

const posts = this.http.get("https://myApi.com/posts?userId=1");
const albums = this.http.get("https://myApi.com/albums?userId=1");

forkJoin([posts, albums]).subscribe((result) => {
  this.combineResults(result[0], result[1]);
});

combineResults(res1, res2) {
  const message = res1.text + res2.text;
  console.log(message);
}

Answer №1

To achieve this, utilize the forkJoin method. However, it is essential to manage errors for each individual sub Observable by using catchError to avoid interrupting the stream in case of any errors.

You can implement something similar to the code below:

// import { catchError } from 'rxjs/operators';
// import { forkJoin, of } from 'rxjs';

const posts = this.http
  .get('https://myApi.com/posts?userId=1')
  .pipe(catchError((err) => of(err)));
const albums = this.http
  .get('https://myApi.com/albums?userId=1')
  .pipe(catchError((err) => of(err)));

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});

Answer №2

To enhance reusability and facilitate unit testing, I propose creating a custom function called forkJoinReplaceErrors. This function takes an array of Observables and an ObservableInput as parameters. It then maps each Observable in the array to catch any errors and replace them with the provided ObservableInput.

function forkJoinReplaceErrors<T,R>(
  observables: Observable<T>[],
  ifError: ObservableInput<R>
) {
  const returnIfError = () => ifError;
  const modifiedArray = observables.map(
    observable => observable.pipe(
      catchError(returnIfError)
    )
  );
  return forkJoin(...modifiedArray);
}

This custom function can be used instead of calling forkJoin directly, making it more reusable and easier to test individual components.

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

Determining the clicked node in a JavaScript environment

There are multiple spans with labels. <span class="viewEdit">View and edit class one.</span> <span class="viewEdit">View and edit class two.</span> <span class="viewEdit">View and edit class three.</span> <span clas ...

Utilize Angular functions in every controller in your application

Currently, I have important functionality code within app.run(function... in Angular: app.run(function($rootScope, $window) { // Obtain window dimensions $window.width = angular.element($window).width(); $window.height = angular.element($window).he ...

I attempted to activate the hover effect on a DOM element using JavaScript, but was unsuccessful. It appears that achieving this is not possible. However, I am curious as to how Chrome is able to

I attempted to activate the hover state of a DOM element using JavaScript, but had no success. It appears that this task is not achievable in the way I initially approached it. I have heard that creating a class with a hover function and then adding or ...

Struggling with properly navigating a JSON file in my JavaScript code... specifically trying to access and retrieve the "responseObject.weather[i].weatherresponseObject.weather[i].description" data

Struggling with extracting data from a PHP file in JSON format to display on an HTML file using JavaScript. I seem to be encountering issues with accessing responseObject.weather[i].weatherresponseObject.weather[i].description, and I suspect it might be d ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

What sets apart `npm install --save-dev gulp-uglify` from `npm install gulp-uglify`?

I'm feeling perplexed regarding the npm installation process. Based on what I've gathered, there are several options available to me when installing modules: The -g option which saves modules globally --save-dev No arguments. Could someone cl ...

Is the `visibility: hidden` property not functioning as expected?

I am trying to conceal the script for the photoset until it is fully loaded, but unfortunately the code below does not seem to be effective: JavaScript $('.photoset-grid').photosetGrid({ rel: $('.photoset-grid').attr("data-id"), gutte ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

MatTooltip component in Angular Material UI is malfunctioning

In my angular component within a hybrid application, I have incorporated the mattooltip directive with links. However, I am facing an issue where the tooltip position is not accurate when hovering over the first link. Sometimes, the tooltip appears empty o ...

Two functions are contained within an object: Function A and Function B. Function A calls Function B from within its own code

If I have two functions within an Object. Object = { Function1() { console.log('Function 1') }, Function2() { this.Function1() } } The Function1 is not being executed. Can someone explain why this is happening an ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

Unable to transform socket.io event into Bacon EventStream

After successfully binding the event on socket.io, the following code was executed: io = require('socket.io')() io.on 'connection', (socket) -> console.log socket.id io.listen 3000 An attempt was made to convert the socket.io ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Trying to access properties of undefined

I am having trouble adding the form control class to my select statement. The issue arises when props become undefined. Here's the code snippet: const useStyles = makeStyles({ root: { width: "100%", maxWidth: 500 } }); const cl ...

Exploring the depths of web automation using Python and Selenium, harnessing the power of a while

Currently, I am navigating through various pages on iens website using Selenium and Python. My goal is to click on the "Volgende" button (which means "next" in Dutch) continuously until there are no more pages left by implementing a while loop. Specificall ...

Assign a distinct color to each character of the Russian alphabet within a specified text using CSS and/or JavaScript

My experiment involves testing the concept of "induced synesthesia" by assigning different colors to individual characters in text. I plan to map each character in the Russian alphabet to a specific color, for example, A is red, B is blue, and so on, resul ...

Incorporating Tinymce into a dialog with Vuejs & Vuetify may necessitate a refresh

I have implemented tinymce as a component for creating and editing articles In addition, I am using vuetify along with the v-dialog component, and all my form fields are within this modal However, each time I change the instance of the tinymce component, ...

Showing or hiding components within ReactJS based on conditions from other components

A custom hook has been created to toggle the visibility of a list when a button is clicked. Below is the snippet of the custom hook: import { useEffect } from "react"; import { useState } from "react"; function useVisibilityStatus() { ...

The Axios.catch method does not handle network or console errors

Utilizing React with axios and redux-promise poses a challenge when it comes to handling 404 errors. See the example below: This is the snippet of code causing the issue: const url = FIVE_DAY_FORECAST_URL.replace("{0}", city); axios.interceptors.resp ...