Search code examples
typescriptfunctionmethodsasync-awaitresponse

How to prevent second method getting called before first method called in typescript?


I need to call a method after a API call. I have written the code like this

getData(): void {
  this.apiCall();
  this.processAPIData();
}

The processAPIData() method should be called only after the apiCall() is completed and returned a response either success or true. In certain cases, the apiCall() is taking more time to return a response and the processAPIData() is getting called before the apiCall() is finished. That is causing few issues in the functionality. I have tried using setTimeout() for processAPIData() but there are chances that the apiCall() might take longer time than the time period mentioned in setTimeout.

I don't want to write the processAPIData() inside the body of apiCall() due to specific requirements and conditions. So can someone kindly help me in resolving this problem.

EDIT: Since some of you have asked about apiCall() structure, I am adding the sample structure of it.

apiCall(): void 
{
       this.getAPIData().subscribe((response) => {
       this.dataToBeProcessed = response.data;
      });
}

Solution

  • What you're trying to achieve is possible with async functions and Promises.

    First of all, you will need to make this.apiCall an async function. This makes sure it returns a promise and you can await it.

    async apiCall() {
      const res = await this.getAPIData().toPromise()
      this.dataToBeProcessed = res.data
    }
    

    To be able to wait for the result of apiCall, you'll also need to make getData async:

    async getData() {
      await this.apiCall()
      this.processAPIData()
    }
    

    EDIT: Use new information provided by OP