React class component issue in order of execution

60 Views Asked by At

I have the following code in my React class component.

For some reason, I am observing that, inside componentDidMount, despite having the keyword await before the call to this.getKeyForNextRequest(), the execution is jumping to the next call, this.loadGrids().

Am I doing something wrong here?

async componentDidMount() {
    await this.getKeyForNextRequest();
    await this.loadGrids();
}

getKeyForNextRequest = async () => {
    const dataRequester = new DataRequester({
      dataSource: `${URL}`,
      requestType: "POST",
      params: {
      },
      successCallback: response => {
        console.log(response);
      }
});

dataRequester.requestData();
}
loadGrids = async () => {
    await this.loadGrid1ColumnDefs();
    this.loadGrid1Data();
    await this.loadGrid2ColumnDefs();
    this.loadGrid2Data();
}
1

There are 1 best solutions below

0
On

You can try using the Promise constructor:

getKeyForNextRequest = () => {
  return new Promise((resolve, reject) => {
    const dataRequester = new DataRequester({
      dataSource: `${URL}`,
      requestType: "POST",
      params: {},
      successCallback: response => {
        console.log(response);
        resolve(response);
      }
    });
  });
}

This ensures you're waiting for a relevant promise, one that resolves only upon successCallback completing, rather than one that resolves instantly to undefined as you have it currently.

This is called "promisifying" the callback.

If DataRequester offers a promise-based mode, use that instead of promisifying the callback.