Run two observables concurrently without needing to transform them into promises

I am in need of a way to simultaneously call multiple API endpoints asynchronously. I have Observable results from individual API calls, but what I really want is to gather all these results together and be able to handle them collectively, with an option to manage any exceptions that may occur. It's like the Angular equivalent of asyncio.gather(). I don't wish to convert observables to promises or resort to outdated methods like forkJoin() or the async pipe. Is there another solution available for this problem?

Answer №1

forkJoin is not deprecated at all; however, certain variations of it may be considered as such. An array of Observables or a dictionary can serve as valid inputs for forkJoin.

You should not see any deprecation warnings when using this.

const sources$: Observable<any>[] = [obs1$, obs2$, obs3$]
forkJoin(sources$).subscribe()

Answer №2

Instead of 'converting' observables to promises (assuming reference to toPromise()), the approach here is to wrap subscriptions in promises and use Promise.all() for concurrent await.

  constructor(private http: HttpClient) {}

  async waitForResponses() {
    const obs1 = this.http.get('api1');
    const obs2 = this.http.get('api2');
    const obs3 = this.http.get('api3');

    const promise1 = new Promise((resolve) =>
      obs1.subscribe((result) => resolve(result))
    );
    const promise2 = new Promise((resolve) =>
      obs2.subscribe((result) => resolve(result))
    );
    const promise3 = new Promise((resolve) =>
      obs3.subscribe((result) => resolve(result))
    );

    const [result1, result2, result3] = await Promise.all<any>([promise1, promise2, promise3]);
    
    console.log(result1);
    console.log(result2);
    console.log(result3);
  }

This method allows awaiting all API calls concurrently with flexibility on the order. Results are returned as an array at their respective index correlating with the promise. This likely meets your intended outcome.

Error handling:

    const promise1 = new Promise((resolve, reject) =>
      obs1.subscribe({
        next: (result) => resolve(result),
        error: (err) => reject(err),
      })
    ).catch((err) => console.log(err));

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

jquery quicksearch component for searching is malfunctioning

Utilizing a jquery plugin known as quicksearch to filter a list of comments. Below is an excerpt from the markup: <ol class="commentlist"> <li class="comment byuser comment-author-admin bypostauthor even thread-even depth-1" id="li-com ...

Exploring the world of Vue and Pinia: managing and accessing data like

While delving into Vue and Pinia, I encountered a data management issue on the user side. On my main page, I showcase categories and auction items. However, upon navigating to a specific category in the catalog, the data for auction items remains in the st ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Exploring the power of dynamic templates in Angular 4

After exploring numerous blog posts and discussions, I have yet to discover a solution for my template dilemma. The issue revolves around our straightforward icon component, where users can specify the desired icon and size directly in the template: impor ...

Creating unique custom renders in Node.js

I am in the process of creating an API using node.js and express. I am interested in enhancing the standard res.send function from any of the external route files to format the response beforehand and include extra data. Is there a way to achieve this? A ...

Disabling caching in bootstrap tabs for loading ajax content

My goal is to make bootstrap tabs load content through ajax queries. While this process is straightforward with Jquery tabs, which default to loading content via ajax query, it seems to be a different case for bootstrap. As such, I have come across the fo ...

Button activated on second click

As I am working on a project, I encountered an issue with two buttons and one input field. The input field is supposed to take the value of the clicked button, but currently, the function works only after the second click on the button. I have tried using ...

How can I retrieve the offset value for a user selection using momentjs?

Within my web application, users are prompted to choose a specific time that includes hours, minutes, and a designated timezone. This user selection plays a crucial role in triggering a function on my webserver at the specified time. However, when a user ...

What is the most efficient method for transforming an index into a column number that resembles that of Excel using a functional approach?

Is there a way to write a function that can produce the correct column name for a given number, like A for 1 or AA for 127? I know this question has been addressed numerous times before, however, I am interested in approaching it from a functional perspect ...

What could be causing jQuery's Promise.reject to fail?

Currently, I'm dealing with a REST API that resembles this stub: Snippet 1 (example based on Ruby on Rails). I have some existing jQuery code using classic callbacks: Snippet 2 It's running with these logs: case 1: [INFO] /api/my/action1: rece ...

Encountering a CLI error while attempting to run the 'ng serve

ng : Error encountered while trying to run ng serve. The file C:\Users\Lenovo\AppData\Roaming\npm\ng.ps1 is not digitally signed and cannot be loaded due to security reasons. To learn more about running scripts and adjusting e ...

Submitting forms from a different router in React can pose a unique challenge

As a beginner in React, I am working on creating a simple meal app. In my App component, I am fetching meal data from an api and allowing users to click on a meal for more details. However, I am facing an issue where searching for a new meal on the detail ...

Unable to employ the .some() method with an array consisting of objects

I am currently attempting to determine whether my array of objects contains an attribute with a specific value. I wanted to use the array.some() method instead of a foreach loop, but I keep encountering an error: Error TS2345: Argument of type '(ele ...

Implement the use of `require` to update the `$watch` in an

As a new Angular user, I am facing an issue that involves having two directives in my HTML code like this: <parent-dir param="par"> <child-dir></child-dir> </parent-dir> And defining them in my JavaScript code as follows: In t ...

Include row identification and row information using a multidimensional array structure

When working with the jQuery DataTables plugin, you have the option to utilize arrays of objects or arrays of arrays. It appears from this source that using the object format comes with reserved keys that are managed by the plugin. In my case, I prefer us ...

Eliminating the parent property name from the validation message of a nested object

When using @ValidateNested() with the class-validator library, I encountered a formatting issue when validating a nested object: // Object Schema: export class CreateServerSettingsDTO { @IsNotEmpty({ message: 'Username is required' }) usernam ...

What is the specific term for an event that exclusively passes type arguments into a generic function within the realm of TypeScript?

Currently delving into the world of typescript generics, I recently crafted a generic function as shown below: function getRandomElement<T>(items: T[]): T { let ranIndex = Math.floor(Math.random() * items.length); return items[ranIndex]; } ...

Creating a dynamic grid layout using a single unordered list (<ul>), with the help of CSS styling and possibly some JavaScript magic

Here is an example of my extensive HTML code, filled with links: <-- language: lang-html --> <ul> <li><a href="/link.html">Link1</a></li> <li><a href="/link.html">Link2</a></li> < ...

Navigating to the designated row within the HTML table even with a scrollbar present

I am working with a table where the selected row is highlighted when a user clicks on it. In another panel, there is a map displaying all employees. Each row in the table has a unique ID and clicking on an employee's image on the map highlights their ...

Learn how to dynamically populate text fields with data when an option is selected from a dropdown menu that is populated from a database using Laravel and Ajax technologies

Basically, I've included a drop-down menu in my form that retrieves values from the database. The form itself contains input fields, some of which already have values saved in the database. I'm using the drop-down menu to automatically load these ...