Is there a way to execute Angular code synchronously similar to how it is done in C#?

Trying to replicate a C# application in Angular is proving to be challenging for me, particularly when it comes to ensuring that the code runs synchronously.

Consider the following example:

private void doChecks()
{
    if (isInvoiced())
        return;

    Console.WriteLine("Done");
}

private bool isInvoiced()
{
    var invID = Server.GetInvoice(mAccID);
    if (invID <= 0)
        return false;
    else 
        return someOtherFunction(invID);
}

When attempting to implement this behavior in Angular, I am uncertain how to achieve the same sequential execution without relying on async/await methods.


async doChecks() {
    const doAllChecks = await this.service.DoChecks(this.mAcc).toPromise();

    if (await this.isInvoiced()) {
      return;
    }
    Console.log("Done");
}


async isInvoiced() {
    const invID = await this.service.GetInvoice(this.mAcc).toPromise();

    if (invID <= 0)
        return false;
    else {
        const data = await someOtherFunction(invID); // Now this function will also need to be async so I can await inside it for its http request to finish.
        return data;
    }
}

Is there a simpler way to achieve this?

Answer №1

To sequentially run multiple functions, you can nest them inside a "then statement" to create Nested Promises. If you are working with Angular 2 or higher, consider nesting your logic within subscribers instead of promises for enhanced functionality.

this.MyPromise1().then(result => {
    this.MyPromise2().then(result2 => {
        this.MyPromise3().then(result3 => {
            // Add more functions here
        })
    })
});

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

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

Avoid unwanted typeof warnings in TypeScript and WebStorm combination

How can I handle unwanted TypeScript checks related to JavaScript usage in today's development environment? Consider the following function: function connect(config: string): void { // Getting warning for the line that follows: // typeof ...

Launching a Node.js application on a Kubernetes cluster

Currently, I have a local Angular 6 application that I run using "npm start." My next goal is to deploy this application in Kubernetes. However, I'm unsure about how to dockerize an Angular 6 based application and run it in Kubernetes. Any assistance ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

typescript max recursion depth restricted to 9 levels

After countless attempts, I finally managed to create a generic type that provides me with all possible combinations of JSON key lists and values. Additionally, I have developed a method to limit the recursion within this type. type EditAction<T,P exten ...

Encountering a Problem on Heroku: TypeScript Compilation Error with GraphQL Files - TS2307 Error: Module 'graphql' Not Found or Its Type Declarations Missing

While trying to compile my typescript project with graphql files for deployment on Heroku, I encountered the following error message: node_modules/@types/graphql-upload/index.d.ts(10,35): error TS2307: Cannot find module 'graphql' or its correspo ...

Guide to automatically opening a webview upon launching an ionic application

After encountering difficulties opening a login page from the desktop site with webview when my ionic app launches, I decided to create a separate page named login-check.page. On this page, I included a button that successfully opens the desktop login page ...

Fixing 404 Errors in Angular 2 Due to Component Relative Paths in SystemJS-Builder

I recently posted this on https://github.com/systemjs/builder/issues/611 My goal is to bundle my Angular 2 rc 1 application using systemjs-builder 0.15.16's buildStatic method. In my Angular component, there is a view and one or more external stylesh ...

The AppModule's CanLoad protector

I recently developed an Angular application using angular-cli and successfully implemented CanLoad guard for my modules. The CanLoad check verifies if the user is logged in before loading a module. My question is, can I apply CanLoad guard to AppModule as ...

Implementing service injection within filters in NestJS

Looking to integrate nestjs-config into the custom exception handler below: import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { InjectConfig } fro ...

UpdatePanel Timer Trigger Failing to Execute

Struggling to make a Timer trigger an UpdatePanel update, but the event won't fire. The examples I'm following are too basic for this issue. I have a lengthy process that evaluates database rows and flags problematic ones. To create a progress p ...

Necessary element for a Web service

Upon reviewing the code example from http://msdn.microsoft.com/en-us/library/dd728281.aspx#Y0, a curious observation was made: removing the Public ReadOnly Property Items() from the OrderItemData class resulted in an error being displayed by the service. T ...

What are the best methods for visually designing a database using Entity Framework Core?

I find myself contemplating the best approach to designing my database scheme for optimal efficiency and visual appeal. Currently, I am working on an ASP.NET Core application with Angular 2, utilizing Entity Framework Core ("Microsoft.EntityFrameworkCore" ...

Leveraging angular-cli to compile a library that can be easily integrated into multiple projects

Let me provide some context: I set up an angular-cli (beta 17) project for my organization that includes multiple components I want to share with other Angular 2 projects within the organization. Initially, I kept it simple by using npm to install the Gi ...

Using Selenium with Internet Explorer Driver in Compatibility Mode

Is there a method to make webdriver/internetexplorerdriver open a site in compatibility mode? Each time I execute my tests using Nunit, the browsing history and compatibility mode list (where my site was previously listed) are cleared. I am unable to alte ...

Angular application experiencing loading issues on Firefox caused by CSP problems

I am encountering an issue while trying to access my app on the testing server. The internal URL I am using is: . However, when I visit the page, it appears completely blank and upon inspecting the dev console, I see the following error message. This situa ...

Is it possible to configure a unique Bearer Access Token in the "angular-oauth2-oidc" library?

For my Facebook login, I have set up a custom endpoint where the client sends the Facebook access token. In my Ionic App, I use the '@ionic-native/facebook/ngx' package to retrieve this token. Within a Laravel Json API controller, I utilize Soci ...

Is including takeUntil in every pipe really necessary?

I'm curious whether it's better to use takeUntil in each pipe or just once for the entire process? search = (text$: Observable<string>) => text$.pipe( debounceTime(200), distinctUntilChanged(), filter((term) => term.length >= ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...