Wait for a specialized occurrence in Typescript before moving forward

I have a function:

async ready():Promise<boolean> {
    await this.myClass.firstToComplete();
    this.myClass.secondToComplete();
}

However, firstToComplete() needs to wait for an event it is listening for before proceeding.

async firstToComplete(): Promise<void>{
   return new Promise(resolve =>  this.anEventListener = () => resolve());
}

Yet, I'm unsure of how to properly structure this in my code.

Here is an overview of my current codebase:

async ready():Promise<boolean> {
             await this.myClass.firstToComplete();
             this.myClass.secondToComplete();
         }

export class myClass{
    private static completion_event = new Event("complete");

    async anEventListener(): Promise<void>{
        await window.addEventListener("complete", function(){
            return
        });
    }

    async firstToComplete(): Promise<void> {
         await this.listening();


    async listening() {
        return new Promise(resolve =>  this.anEventListener = () => resolve());
    }

    private static functionWaitingToComplete() {
        window.dispatchEvent(this.completion_event)
    }

Answer №1

When it comes to events and promises, I have limited experience but here are two approaches that can be taken. The first one involves resolving the promise inside the event, while the second one requires passing the second function as a callback.

For the first option:

const handleEvent = () => {
  return new Promise((resolve, reject) => {
    const onMyEvent= () => {
      resolve("Event occurred");
    };

    window.addEventListener("eventName", onMyEvent);
  });
};

const afterEvent = () => {
  console.log("After event occurs");
};

const asyncOperation = async () => {
  await handleEvent();
  afterEvent();
};

For the second option:

const triggerFunction = (callback: () => void) => {
  const onMyEvent= () => {
    callback();
  };

  window.addEventListener("eventName", onMyEvent);
};

const postEventAction = () => {
  console.log("After event completes");
};

const mainTask = () => {
  triggerFunction(postEventAction);
};

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

What are the steps for developing a basic Typescript node module on a local environment?

Within my repository, I am utilizing multiple node modules for my lambdas. I have some essential functions that I would like to share across these modules. To achieve this, I have created a separate node module at the root of my repository named common. T ...

Transitioning from one provider to another and encountering the error message "Cannot read property prompt of undefined."

This is an example of an alert service in TypeScript public Alert = { prompt: () => { return new Promise((resolve, reject) => { let prompt = this.alertCtrl.create({ title: 'Enter username', ...

Integrate TypeScript into the current project

As a newcomer to Typescript, I am currently exploring the option of integrating it into my current project. In our MVC project, we have a single file that houses the definitions of all model objects. This file is downloaded to the client when the user fir ...

Significant bloat in main.js file detected in Angular 2 application compilation

I developed an application using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="65040b02100904174806090c25554b554b565c">[email protected]</a>. The app is a transformation of a basic Angular 1 application. My conc ...

Avoid saying the same thing more than once

Within my Typescript class, I have the following structure: class C { #fsm (...) startFoo(name: string) { this.#fsm.send('FOO', name) return this } startBar(name: string) { this.#fsm.send('BAR', name) return th ...

Is there a surefire method to ensure that ChromeDriver in Protractor consistently uses the stable version?

Every time Chrome releases an update, I encounter a recurring issue. Allow me to paint the picture: All browsers are at version 83 of Chrome Chrome announces that version 84 is on its way, but it has not been released yet. A new ChromeDriver 84 is rolled ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Retrieving data from Redis cache may not always yield the exact same data

I have been working on creating a small Express app that retrieves data from a PostgreSQL query and caches the result in a Redis database. Here is my approach: app.get('/query_tile/:z/:x/:y', async (req: Request, res: Response) => { const ...

Issue with Angular trackBy not functioning properly within a nested *ngFor loop

My component is similar to the following <div class="users-list" *ngIf="datasetPermission !== undefined"> <div *ngFor="let userpermission of datasetPermission; trackBy : trackByFn"> <span *ngFor="let user of userpermission.users"& ...

Tips for triggering useEffect just once when various dependencies are updated simultaneously

Currently, I have implemented a useEffect hook with two dependencies in the following way: useEffect(() => { ..... }, [apiData, currentMeasurements]); It's important to note that the apiData is fetched using useLazyQuery from apollo/client. Upon ...

Exploring the synergy between Visual Studio 2015 and Angular2 Beta 2's dependency injection functionality

Currently, I am using VS2015 alongside TypeScript 1.7.3 and Angular2 Beta 2 with a target of ECMA 5. In order to enable experimental decorators in my project, I have made modifications to the csproj file by including TypeScriptExperimentalDecorators = true ...

Stop VueJs RouterView's Transitions from triggering on carousel initialization

As I dive into the world of VueJs (3), I've implemented a transition effect on my routes to give my pages a smooth appearance. Everything seems to be working well, but there's one issue - when I refresh the page (F5) or on first load, the transit ...

Filtering through an array object with PrimeNG

Is it feasible to utilize an array of objects for filtering data in a table? I'm currently using Angular 6 and PrimeNG 7. This is how my p-table appears: <p-table #table class="ui-table ui-table-responsive" [value]="arrays" [columns]="cols" > ...

Angular 16 HttpClient post request with asynchronous action

Here I am working on integrating JWT in Angular with a .Net Core API. When I start my Angular server and launch the application, I encounter the following scenarios: Attempting with correct credentials initially fails, but retrying allows it to work. Tryi ...

Issue Encountered When Integrating a StencilJS Component Library with NextJS

I have my own StencilJS component library hosted privately on GitLab. While I can successfully use it in regular HTML, I'm facing issues trying to integrate the StencilJS Web Components into a NextJS app. When attempting to do so, I encounter the fol ...

What is the best way to combine two arrays and generate a new array that includes only unique values, similar to a Union

Here are two arrays that I have: X = [ { "id": "123a", "month": 5, "markCount": 75 }, { "id": "123b", "month": 6, "markCount": 85 ...

The TS2769 error occurs when trying to change the react calendar due to no matching overload in the

The calendar functionality in my project was implemented using the response calendar library. Suddenly, I encountered an onChange prop error in the default code. This was working fine before. What steps should I take to resolve this issue? Here is my cod ...

Display fresh information that has been fetched via an HTTP request in Angular

Recently, I encountered an issue where data from a nested array in a data response was not displaying properly in my component's view. Despite successfully pushing the data into the object programmatically and confirming that the for loop added the it ...

Navigating an array using ngFor and encountering an error message saying, "Identifier not specified"

While using ngFor to iterate through an array, I encountered the following error message: "Identifier 'expenseitem' is not defined. The component declaration, template variable declarations, and element references do not contain such a memb ...

What is the best way to attach a button to a mat-drawer?

I am facing an issue with aligning a button to a mat drawer located to the right of the screen to ensure a clear overall design. Check out this example How can I achieve this alignment? My current approach involves placing the button inside the drawer an ...