The forkJoin method fails to execute the log lines

I've come up with a solution.

private retrieveData() {
     console.log('Start');
     const sub1 = this.http['url1'].get();
     const sub2 = this.http['url2'].get();
     const sub3 = this.http['url3'].get();
     const sub = forkJoin([sub1, sub2, sub3]).subscribe(([res1, res2, res3]) => {
         console.log('Merging data');
         this.list1 = res1 as ProjectDto[];
         this.list2 = res2 as Array<MyTest>;
         this.list3 = res3 as Array<MyTest>;
         sessionStorage.setItem('a', JSON.stringify(this.list1));
         sessionStorage.setItem('b', JSON.stringify(this.list2));
         sessionStorage.setItem('c', JSON.stringify(this.list3));
         console.log('Data saved successfully');
     });
     console.log('Process complete');
   }

After calling the method, I noticed that two log lines within the forkJoin were not being triggered. This made me uncertain about whether the data was fetched from the service. I am utilizing rxjs version 5.5.6.

UPDATE:

Upon further inspection, I realized that the logs were indeed being printed, but due to the prolonged execution time of the service. As a result, the issue now revolves around how to ensure synchronous log printing. Currently, 'Start' and 'Process complete' are displayed first.

Answer №1

When working with the subscribe function, the third parameter is crucial as it accepts a callback that will be triggered once the stream is finished.

const subscription = forkJoin([source1, source2, source3]).subscribe(([result1, result2, result3]) => {
     console.log('Using forkJoin');
     this.dataList1 = result1 as ProjectDto[];
     this.dataList2 = result2 as Array<MyTest>;
     this.dataList3 = result3 as Array<MyTest>;
     sessionStorage.setItem('x', JSON.stringify(this.dataList1));
     sessionStorage.setItem('y', JSON.stringify(this.dataList2));
     sessionStorage.setItem('z', JSON.stringify(this.dataList3));
 }, null, () => console.log('Operation completed'));

Answer №2

To ensure proper synchronization, it is recommended to place the console.log('Completed'); statement inside the subscribe function. This is because the subscribe function is asynchronous and executes at a later time.

If you prefer to maintain the same structure, you can utilize a promise-based approach in your programming logic.

import { take } from 'rxjs/operators';
....
private async fetchData(): Promise<boolean> {
     console.log('Begin');
     const sub1 = this.http['url1'].get();
     const sub2 = this.http['url2'].get();
     const sub3 = this.http['url3'].get();
     const [res1, res2, res3] = await forkJoin([sub1, sub2, sub3]).pipe(take(1)).toPromise();
     console.log('fork join');
     this.list1 = res1 as ProjectDto[];
     this.list2 = res2 as Array<MyTest>;
     this.list3 = res3 as Array<MyTest>;
     sessionStorage.setItem('a', JSON.stringify(this.list1));
     sessionStorage.setItem('b', JSON.stringify(this.list2));
     sessionStorage.setItem('c', JSON.stringify(this.list3));
     console.log('set items');
     console.log('Completed');
     return Promise.resolve(true);
   }

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

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Guide to Angular 6 Reactive Forms: Automatically filling one text field when another input is selected

I'm currently learning Angular 6 and exploring reactive forms. I want to set up a feature where selecting an option in one field will automatically populate another field. The objective is to have the coefficient input update based on the number sele ...

How can I most effectively establish defaultValues for react-hook-form in this scenario?

I am working on a static Next.js website with only frontend functionality. In the pages/feedback/[id]/edit.tsx page, I need to dynamically retrieve an id and set default values in a nested FeedbackForm component. export const FeedbackForm = ({ editing }: { ...

Execute an AJAX function to monitor a JSON response at intervals of 3 seconds

I'm looking to verify if my user has been updated from another system using JavaScript. Can anyone assist me in creating a function that can analyze a JSON response and determine if it is true or false? The URL /user/updatecheck/ provides a JSON res ...

How to access a particular tab in Bootstrap 5 using an external link

Is there a way to direct users to a specific tab upon clicking a link on another page? Check out the example below: <div class="products-btn"> <a href="products.html#pills-profile">view all</a> </div> On Pro ...

Displaying dynamic data with Vue.js and Chart.js

I am currently working on a VueJS code to display a bar-chart: Vue.component('bar-chart', { extends: VueChartJs.Bar, data: function () { return { datacollection: { labels: ['MICROFINANZAS -SECTOR C ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

Objects in the array are failing to sort in the expected sequence

I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order. var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'}, ...

Angular 11 Import Guide for MAT_DATE_LOCALE

I am struggling with importing 'mat-date-locale' in Angular 11 modules. The link I followed didn't provide a solution, as mentioned here: Cannot find name "MAT_DATE_LOCALE" with Material.angular Datepicker. In my project, I have A ...

The complete rendering of angular-google-maps is only achieved after resizing the browser

<ui-gmap-google-map center="{latitude: 43.100187, longitude: -77.6329959}" zoom='8'> </ui-gmap-google-map> https://i.sstatic.net/9F2eb.jpg All necessary files were loaded via bower and the dependency was added t ...

Encountered an issue with undefined property when attempting to add a second value to an array of

I have been working on the following javascript code: var res = [{}]; for (var idx = 0; idx < json.length; idx++) { // if the environment is already entered in the result if (res[idx].env) { sails.log.debug('Enviro ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

A Comprehensive Guide on Implementing String Values in Highchart Series

When attempting to pass a string value (data) to the highchart series, I encountered an issue where it would display a blank chart. Is there a specific way to use a string value in the series of the highchart jQuery plugin? var data="{name: 'Jane&apo ...

Node.js server allows for accessing AJAX requests seamlessly

I need to send a parsed AST of JavaScript code to a server for processing, and then receive a list of completions back. However, when I log the AST to the client console before sending it, the structure appears like this: [ { "id":0, "type":"Program", "ch ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

Different div elements are clashing with each other when it comes to hiding and

Having added multiple div elements with different IDs, I am facing an issue where clicking one div displays it while hiding the others. I am looking for a solution to prevent conflicts between the divs. Any suggestions on what might be causing this problem ...

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Replace Original Image with Alternate Image if Image Error Occurs Using jQuery (Bootstrap File Input)

I am currently utilizing the Bootstrap File Input component for file uploads, and it's working splendidly. I have set up the initialPreviewConfig to display the existing image on the server. However, there are instances when there is no file available ...

Tips for creating a stylish, blurred, and centered box for a login form on a full-size background that is also responsive

I attempted to create a login form on an HTML page using Angular, featuring a full-size background image that is centered. The form itself is contained within a div with a blurred background, also centered both horizontally and vertically within the browse ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...