Tarun
Tarun

Reputation: 848

sequencing async/await calls in TypeScript

I have the following code snippet.I am facing a problem that sometimes the sequence is not honored i.e _doSomethingNext( )is called before _doSomethingFirst( ).

<CustomModal
  onDissmiss( ): { ( )=> { 
     executeInSequence( );
  }
}
/>
private executeInSequence( ):void {
   this._fun1( ).then(( ) => { this._fun2(); });
} 
private async _fun1( ):void {
  const result: IResultArray[] = await httpClient1.getData ();
    if (!result) {
        this._doSomethingFirst();
    }
}
private async _fun2( ):void {
  const result: IResultArray[] = await httpClient2.getData ();
    if (!result) {
        this._doSomethingNext();
    }
}

Any idea why is this happening and how do I ensure sequence and only single call to await calls to getData( ).

Upvotes: 1

Views: 425

Answers (1)

Jeroenouw
Jeroenouw

Reputation: 157

You should have return statements and async keyword like this;

private async _fun1( ) {
  const result: IResultArray[] = await httpClient1.getData ();
    if (!result) {
        return this._doSomethingFirst();
    }
}

private async _fun2( ) {
  const result: IResultArray[] = await httpClient2.getData ();
    if (!result) {
        return this._doSomethingNext();
    }
}


Upvotes: 1

Related Questions