What is the best way to ensure an observable has finished before retrieving a value?

Looking at the function provided below:

 public getAssemblyTree(id: number) {
        ....
        const request = from(fetch(targetUrl.toString(), { headers: { 'responseType': 'json' }, method: 'GET' }));

        request.subscribe(
            (response) => {
                response.json().then(data => {
                    assemblyNodesForTree.push(...this.parseAssemblyTree(data['flat_assembly_graph']));
                }
                )
            }
        )
        console.log(assemblyNodesForTree)
        return assemblyNodesForTree;
    }

I noticed that the function is returning `assemblyNodesForTree` before the observable has completed. I'm curious to know what might be the correct approach for handling this situation?

Answer №1

Are you considering converting an asynchronous operation to run synchronously? You might find the solution to a similar issue in this related question Problem returning value from RxJS Observable.


Here's a quick suggestion: try using fromFetch instead of from(fetch)

Why choose fromFetch? Because it utilizes the fetch API internally and completes the observable once the API call is complete.

You seem to be subscribing within the getAssemblyTree function, which will be invoked after the AJAX request finishes. However, instead of just returning at that point, consider returning the assemblyNodesForTree variable for better results as the current method will always return empty.

To handle the asynchronous behavior, you can use operators in your observable pipe and perform necessary operations within the map operator function. Lastly, ensure to return either a Promise or Observable from the getAssemblyTree function.

public getAssemblyTree(id: number) {
    ....
    const request = fromFetch({
      url: targetUrl.toString(), 
      headers: { 'responseType': 'json' }, method: 'GET' 
    }).pipe(
       map(async (response) => {
          const assemblyNodesForTree = [];
          const data = await response.json()
          assemblyNodesForTree.push(
            ...this.parseAssemblyTree(data['flat_assembly_graph'])
          );
          return assemblyNodesForTree;
       })
    );
    return request;
}

Example Usage

async myFunction() {
  const assemblyNodesForTree = await lastValueFrom(getAssemblyTree(id))
}

Implementing this function is straightforward - simply call the getAssemblyTree(id) function with lastValueFrom() wrapper. Upon completion of the fromFetch API call, the promise will be resolved.

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

Emphasize the close button within the popup window as soon as it appears

One of my coding challenges involves a div element, shown below: <div id="modal" tabindex="-1" ng-show="booleanvariable"></div> When the value of ng-show is true, this div is displayed. A "close" button located under the div should be focused ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

Changing Enum Value to Text

In my enum file, I have defined an object for PaymentTypes: export enum PaymentTypes { Invoice = 1, CreditCard = 2, PrePayment = 3, } When I fetch data as an array from the database, it also includes PaymentType represented as numbers: order: ...

Ways to link two PHP scripts

My code snippet below aims to select a location from a dropdown menu and generate a pie chart based on data fetched from a PostgreSQL database. However, I am facing an issue where the pie chart displays all column values instead of only the selected locati ...

Leveraging backstretch.js in combination with blur.js (or equivalent)

Query Update I provided a response to the query below, however, I am experiencing some lag and a noticeable stepped transition between images. Can anyone offer advice on how to optimize this issue? Perhaps it would be better to go back to using a static ...

What is the best way to retrieve an element from an array within a script?

As a newbie in the realm of vue and Laravel Framework, I am eager to fetch data from an API and display it dynamically on my web page. To achieve this, I have already set up a table named 'Progress' where I seeded some initial data. Utilizing AP ...

Searching function in material-table does not work properly with pipe symbol

Within my data table, I utilize the @pipe to display name instead of position in the position row... The name is sourced from a separate JSON file... <ng-container matColumnDef="position"> <mat-header-cell *matHeaderCellDef> No. </ma ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

JavaScript can be utilized to manage the exit events

Possible Duplicate: Alert when browser window closed accidentally Is there a way to trigger a new window to open when a user clicks the exit button (X) on the browser, similar to how the Wordpress Admin Panel functions? In the Wordpress panel, when t ...

Using Jquery to toggle columns based on their index and custom attribute

My table has two rows in the header: the first row with colspan and the second row containing headers. You can see an image below for reference. https://i.sstatic.net/qwSBL.png With a jQuery function, I extract all the table cell values from the second h ...

Error: Angular 2 Application lacks 'Access-Control-Allow-Origin' header

Currently, I am working on a project where I am focusing on learning and practicing Angular 2. Since I do not have a server-side setup, I am making API requests to the barchart ondemand api. I am facing an issue with CORS and I am wondering if there is a ...

Setting up and using npm jshint with Grunt and Node.js

I have successfully installed node.js on Windows with the npm package. My project is located in the D drive at D:>projectD I am currently working on running jshint along with SASS, concat, etc. Everything seems to be working fine except for jshint ...

Having trouble showing my Google map using canvas

Can anyone help me with this issue that I'm facing? I am working on a JavaScript web page and trying to show a Google map (Google API) along with a canvas tag in the html body. Currently, the map and canvas are only displaying separately. https://i ...

Showing various divisions based on the selected option from a dropdown menu

My goal is to have forms display below a select tag based on the number selected by the user. I am attempting to achieve this using JQuery, but it's currently not functioning as expected: Select tag:- <label>How many credit cards do you have:* ...

Using ESLint to enforce snake_case naming conventions within TypeScript Type properties

When working with TypeScript, I prefer to use snake_case for properties within my Interfaces or Types. To enforce this rule, I have configured the ESLint rule camelcase as follows: 'camelcase': ["error", {properties: "never"}], Even though the E ...

Trigger the onclick method by selecting an icon within the MUI DataGrid

Currently, I am utilizing the default MUI Dialog model in the "DialogModel.js" component. Additionally, I have integrated another MUI DataGrid component as shown below: // RulesTable.js import * as React from 'react'; import { DataGrid } from &a ...

What could be causing my PrimeReact dropdown component to ignore the custom class styles?

Within my Project, I am utilizing multiple Prime React dropdown components and I am aiming to customize one of them with a unique style. In my CSS, I have established global styles to overwrite the default settings for all the dropdowns. However, when tryi ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

Encountered an error while attempting to install the DataTables npm package in an Angular

I am trying to add datatables to my angular application. Upon running ng add angular-datatables An error code is displayed (refer to the image). error image The cause of this error is unknown to me. Please review the package.json file as well. package.j ...