Executing the calling statement once all function statements have been completed

I am currently working on a lengthy function that involves retrieving data from multiple levels of a database.

  getResult() {
    this.appService
      .getCountries()
      .subscribe(
        (countries: Country[]) => {
          this.countries = countries;
        },
        () => {},
        () => {
          for (let country of this.countries) {
            let cities: City[] = [];
            this.appService
              .getCities(country.id.toString())
              .subscribe(
                (theCities: Cities[]) => {
                  cities = theCities;
                },
                () => {},
                () => {
                  for (let city of cities) {
                    if (city.population>1000) {
                      console.log(city);
                    }
                  }
                }
              );
          }
        }
      );
    this.result = true;
  }

Once all operations are completed, I expect the statement

this.result = true;

to be executed. However, it seems to be triggered before the previous code finishes execution.

Even when placed at the end of the onCompleted function, the

this.result = true;

is invoked before the loop is fully completed.

Answer №1

In my opinion, a more streamlined approach would be to utilize the .toPromise() method after each function call, and transition to using async/await syntax. This way, you can still leverage familiar imperative constructs like for loops while improving readability and maintainability.

  async fetchResultData() {
    this.countries = await this.appService.getCountries().toPromise();
    for (let country of this.countries) {
      const cities: City[] = await this.appService
        .getCities(country.id.toString())
        .toPromise();
      for (let city of cities) {
        if (city.population > 1000) {
          console.log(city);
        }
      }
    this.dataFetched = true;
  }

Answer №2

To maintain your existing code structure without making major changes, consider implementing a counter.

getResult() {
    let count; // adjustment made here
    this.appService
      .getCountries()
      .subscribe(
        (countries: Country[]) => {
          this.countries = countries;
          this.count = this.countries.lent // adjustment made here
        },
        () => {},
        () => {
          for (let country of this.countries) {
            let cities: City[] = [];
            this.appService
              .getCities(country.id.toString())
              .subscribe(
                (theCities: Cities[]) => {
                 count-- // adjustment made here
                  cities = theCities;
                },
                () => {},
                () => {
                  for (let city of cities) {
                    if (city.population>1000) {
                      console.log(city);
                    }
                  }
                 if(count===0)this.result = true // adjustment made here
                }
              );
          }
        }
      );
    // this.result = 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

Guide on extracting data from a JavaScript table using Python

Looking to extract information from a table on this page: . There are a total of 18 pages, but the url remains constant for each page. My usual method involves using BeautifulSoup to scrape data from HTML pages. However, in this case, the required data is ...

When an error occurs while trying to execute a promise more than once, the message "Attempting to access an undefined property

Currently, I am tackling asynchronous issues by using promises. The strange thing is that when I run the promise for the first time, everything works perfectly. However, if I execute the same function twice, it throws a "Cannot read property of undefined" ...

Creating a login system in Node.js with the help of Express

I'm currently working on building a login feature for a website using node.js with the express framework. The code seems to be running in an unexpected order and I'm having trouble figuring out how to resolve it. Below is a simplified version of ...

Flashing occurs while utilizing animation and scrolling

$('.mainNav a[href^="#"]').on('click', function (event) { var target = $(this.getAttribute('href')); if (target.length) { event.preventDefault(); $('body').stop(true).animate({ scrollTop: targe ...

Bypass VueJs Typescript errors within the template section with Typescript

My VueJs App is functioning properly, but there is one thing that bothers me - a TypeScript error in my template block. Is there a way to handle this similar to how I would in my script block? <script setup lang="ts"> //@ignore-ts this li ...

Swapping out one variable for another

After tweaking my code a bit, I'm still struggling to get it right. User input: !change Hi var A = "Hello" if (msg.content.includes ('!change')) { A = msg.content.replace('!change ', ''); } msg.send(A); //the change ...

Attach a click event to images that are dynamically loaded through AJAX

I've been struggling with a particular block of code, and after careful investigation, I believe I have pinpointed the issue. Let me share with you the jQuery function in question... $(document).ready(function(e) { $('#formattingSection&apos ...

Guide on how to execute an API request prior to rendering a component in React JS

export default function Dashboard(){ useEffect(() => { setTimeout(()=>console.log("API Call Completed"),5000) },[]) return( <div> <h1>Dashboard</h1> </div> ...

The initial click on a jQuery event is not registering as expected

My webpage includes a code snippet like this: $('#language_id').change(function () { var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id; $.ajax({ type: "GET", url: urli, dataType: &ap ...

AngularJS (ui-mask) provides a valid input mask feature

i encountered an issue while trying to create an input mask using ui-mask in AngularJs. I want the textarea to turn green when the entered string is correct. However, in my case, the textarea starts off green and then turns red when a word is typed until t ...

Utilizing React/Redux to perform individual fetch calls for specific routes

I have a Redux store that needs to be connected to my App, but I only want to fetch data relevant to the component currently rendered by react-router. Currently, it is connected to a container element (App.js) which passes all props to the router's c ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

Harmonizing various client viewpoints in a ThreeJS scene featuring a unified mesh structure

I am fairly new to ThreeJS and I am curious to know if it is possible to achieve the following, and if so, how can it be done: Two web browser clients on separate machines want to load the same html-based Scene code, but view it from different perspective ...

What is the proper way to define a tuple type with a specific size N for the vector class in C++?

I am seeking to create a tuple type with a fixed size N, allowing for functionality such as: let tuple: Tuple<string, 2> = ["a","b"] In this scenario, "number" represents the type T, and "2" denotes the size N. Subsequently, I ai ...

What is the easiest method for querying one-to-many connections in Django?

Looking for a more efficient way to return a dictionary in JavaScript that includes data from both a Category table and Sub_category table. The desired format is 'Category1': 'Sub_cat1, Sub_cat2, ...'. Any ideas on a better approach? T ...

Utilizing an observer to encapsulate a custom React hook- a comprehensive guide

As part of my project, I have developed a unique custom react hook that relies on observable state from the store for its dependencies within useEffect: Here is an example of my custom hook: const useFoo = (() => { const { count } = store; useEff ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

Align a single item to the right in PrimeNG p-menubar

I am currently utilizing PrimeNG 8.1.1 and I am looking for a way to align one of the items to the right side (specifically the submenu options of logout and profile). Does anyone have any suggestions? this._menuItems = [ { labe ...

Data obtained from the server includes JSON objects along with quotes and regular expressions

While analyzing the functionality of a search page server through element inspection, it was observed that requests are sent via POST with JSON parameters. To verify this observation, I recreated the same POST request using Insomnia with identical paramete ...

Unusual actions observed in Ionic 3 app using webview 3 plugin

I am currently facing a significant problem with Webview 3. One of our developers upgraded it to webview 3 without utilizing the Ionic native webview plugin, and surprisingly, it is functioning well on our Ionic 3 application. As per the documentation avai ...