Is it possible to determine if an object is waiting for an asynchronous member function in TypeScript?

Currently, I am developing the client-side of a web application using TypeScript. Within my own makeshift "framework," I have crafted a class called ViewBinder which employs an asynchronous "show" method to fetch data from the server, extract HTML content, and inject it into the document within a designated "placeholder" element. Subsequent classes derived from this one can then link data from a client state object to the loaded HTML.

Below is a snippet of the code from this class for reference purposes (please note that it is not executable):

export class ViewBinder extends PropertyChangedNotifier {
    // Omitted a lot of member details for brevity...

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        // More code here...
    }

    public clear(): void {
        // Further code...
    }
}

In instances where the client state object undergoes modifications while a ViewBinder is in the midst of executing the 'show' command (during either 'loadView' or 'setupAfterShowing'), resulting in invoking the 'clear' method, the issue arises. This inadvertently eliminates the parent element's content where the HTML was planned to be inserted and data bound.

If the ViewBinder encounters difficulty locating a parent element or finding a suitable location within that element to exhibit data, I view it as a flaw and throw an error. Nonetheless, in certain scenarios, the HTML will be legitimately removed while the asynchronous code awaits outcomes.

I have experimented with utilizing 'showWasCanceled' to avoid potential problems, but there are numerous complexities within derived 'setupAfterShowing' methods which could lead to inconsistencies in abandoning operations if 'showWasCanceled' is true.

Therefore, my question poses:

Is there a way for the 'clear' function to ascertain whether the 'show' function is currently being awaited and halt execution until 'show' has completed?

Answer №1

To implement this functionality, one approach is to define specific fields for storing the required information, for example:

private promise;
private resolve;
private reject;

init() {
  this.promise = new Promise((res, rej)=>{
    this.resolve = res;
    this.reject= rej;
  });
}

public asynchronous display(...) {
  ...
  resolve(null); // or reject in case of any errors above
}

public asynchronous reset() {
  await this.promise;
  ...
}

Answer №2

Opting to acknowledge @ABOS's answer, as it aligns with an async/await approach by having clear() await a promise that show() can handle.

Nevertheless, I chose a more traditional route and decided to outline my method here for the benefit of others.

This approach also eliminated the need to turn clear into an async method, which would have triggered extensive async nesting in multiple areas.

Below is a breakdown of how I tackled this:

To begin, I introduced two boolean variables to the class: clearWasCalled and isRunningShow.

Upon invoking show(), it initializes this.clearWasCalled = false and this.isRunningShow = true. Towards the end of show(), it resets this.isRunningShow = false and if this.clearWasCalled === true, then this.clear() will be invoked.

When clear() is triggered, it verifies if this.isRunningShow === true; if affirmative, it marks this.clearWasCalled = true and exits the function.

Hence, while awaiting the show() method, any calls to clear() won't disrupt the execution of show() but will simply set a flag. Once show() completes its task, it checks if the flag was raised and executes the necessary clear action.

Here's a condensed representation in code:

export class ViewBinder extends PropertyChangedNotifier {
    // Numerous internal components not displayed for conciseness...

    public clearWasCalled = false;
    public isRunningShow = false;

    public async show(callbackAfterShow?: (wasSuccessful: boolean) => void): Promise<HtmlLoadViewResult> {
        this.clearWasCalled = false;
        this.isRunningShow = true;
        const loadResult = await this.loadView();
        if (this.clearWasCalled === false) {    // As a precaution...
            loadResult.wasCanceled = true;
        } else {
            await this.setupAfterShowing(loadResult);
            // CODE OMITTED FOR BREVITY
        }
        this.isRunningShow = false;
        if (this.clearWasCalled) {
            this.clear();
            loadResult.wasCanceled = true;
        }
        return loadResult;
    }

    public clear(): void {
        // Prevent clearing while show method is active
        if (this.isRunningShow) {
            this.clearWasCalled = true;
            return;
        }

        // EXECUTE CLEAR OPERATIONS...
    }

}

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

Troubleshooting: ng-If directive malfunctioning in an Ionic Cordova project with Angular

Project details: Using Ionic Cordova Version of Ionic: 7 Angular version: 18.0.3 The *ngIf directive is not functioning as expected. page.html <ion-segment [(ngModel)]="segment" (ionChange)="typeChange($event)"> <ion-segm ...

Adjust the colors of two elements by clicking a button's onclick event

As stated in the title, I have a button in the books component. When this button is clicked, the color of a div within the books component and another div in the navbar component should change. - Below is the code for the books component : export class Bo ...

Typescript: Utilizing function overloading

Is there a straightforward approach to implementing function overload in TypeScript? function Foo( param1: number, param2: string, param3: string, param4: () => void, param5: (xyz: string) => void): void { .... } function Foo( ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

Error: No default Firebase App named '[DEFAULT]' exists. Please remember to call Firebase App.initializeApp() to create the app (app/no-app). This issue is located at the app

Currently, I am in the process of learning how to integrate Firebase Functions into an Ionic + Angular project. My goal is to develop a custom function that retrieves all games from a collection and returns an array sorted by the "count" attribute. Initia ...

When attempting to start the Azure Functions within a Nodejs Monorepo, the runtime fails with an error

My setup involves a nodejs typescript monorepo structured as follows: libraries/ lib1/ lib2/ package.json tsconfig.json web-api/ function1/ function.json index.ts function2/ function.json index.ts host.json package.json ts ...

Utilizing Pipes within a Method in Angular 2 along with Dependency Injection triggers an "Insufficient Number of Arguments" error

I am searching for a solution to incorporate a custom pipe into my class. The custom pipe itself ( referenced from this source, many thanks ) involves injecting a dependency (the DomSanitizationService). import { Pipe, Inject, Injectable } from '@ang ...

Angular2 - Mapping incoming data to predefined interface structures

My component is currently subscribed to data from a service, which returns a BehaviorSubject that I can subscribe to. The data object retrieved contains multiple arrays representing the Label/Value pairs for my dropdowns. I am attempting to type cast each ...

Enhancing Visuals with src="imageUrl within Html"

Is there a way to customize the appearance of images that are fetched from an API imageUrl? I would like to create some space between the columns but when the images are displayed on a medium to small screen, they appear too close together with no spacing. ...

Testing Angular Components: Ensuring Proper Unit Testing of Public Members Intended for HTML Input Only

How can Angular's ng test --code-coverage help with unit testing public variables that are strictly used as direct input in HTML? https://i.sstatic.net/z6j1O.png These variables are eventually placed into other components like this: <ctrl-grid ...

What is the significance of `new?()` in TypeScript?

Here is a snippet of code I'm working with in the TypeScript playground: interface IFoo { new?(): string; } class Foo implements IFoo { new() { return 'sss'; } } I noticed that I have to include "?" in the interface met ...

Ways to incorporate horizontal scrolling in mat autocomplete

I have an Angular app with auto complete functionality. I am trying to add horizontal scroll to the mat-option by applying CSS styles, but it's not working as expected. .cdk-overlay-pane { overflow-x: auto; } I also tried following the instruc ...

Checking for non-falsy variables that include 0 in JavaScript

What is a more graceful method for checking if a variable is truthy but also passes when it's equal to 0? The current verification if(var !== undefined && var !== null) is lengthy and doesn't account for all scenarios such as undefined or ...

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

Typescript functional programming: issue arises during transformation of postgres database output into a view model using fp-ts

Currently, I am facing a challenge in extracting data from a postgresql database, converting it into a view model array, and delivering the information back to the client. My goal is to return the data as a single object instead of an array. However, I enc ...

React application facing a problem with bracket notation in Typescript

After creating a form state to store and update input changes, I encountered an issue: const [form, setForm] = useState({ user: '', email: '', password: '', }); I then wrote a function to handle form changes: const handle ...

Leverage Custom_Pipe within TS

I am currently working with a pipe that I have created. Here is the code: @Pipe({ name: 'searchNomES' }) export class SearchNomESPipe implements PipeTransform { transform(uos: IUo[], name?: string,): IUo[] { if (!uos) return []; if (!name) ret ...

Filtering a multi-dimensional array in Ionic 3

I attempted to filter an array from a JSON with the following structure {ID: "2031", title: "title 1", image: "http://wwwsite.com/im.jpg", url: "url...", Goal: "3000000", …} The array is named 'loadedprojects' and below is the filteri ...

Angular index.html file can include a conditional script

I am currently working on an Angular project, where the index.html serves as the main entry point for the application, just like in any other Angular project. This file contains important links and configurations. Within the HTML code snippet below, you w ...

What is the best way to troubleshoot the type of data being sent to the subscriber of an Angular observable?

I am new to the world of Angular-7, RxJS-6, and Visual Studio Code. Currently, I am facing a challenge with debugging an Observable that is being returned to a subscriber, resulting in a "TypeError" at runtime. It seems like this issue is not uncommon amon ...