0

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();
}
ggorlen
  • 44,755
  • 7
  • 76
  • 106
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 1
    You are not returning a promise from getKeyForNextRequest method – user700284 Apr 26 '21 at 04:47
  • Wouldn't you need to return a promise that resolves to `response` in `successCallback`? `getKeyForNextRequest` returns a promise, but it's one that resolves instantly to `undefined` rather than having anything to do with `successCallback`... – ggorlen Apr 26 '21 at 04:47
  • `getKeyForNextRequest` doesn't return a value so the function immediately resolves. There is nothing to wait for. – Drew Reese Apr 26 '21 at 04:48
  • @DrewReese - Thanks...What do I need to add inside getKeyForNextRequest ? Basically, I set a state/key inside the "successCallback" of getKeyForNextRequest and that is to be used in the next AJAX calls (i.e. for loadGrid1Data) – copenndthagen Apr 26 '21 at 04:49
  • Dunno, depends on what you are trying to wait for I guess. Maybe `return dataRequester` and/or (or both) return a Promise and add a call to resolve to the `successCallback` function? UPDATE: See @ggorlen's answer. – Drew Reese Apr 26 '21 at 04:52

1 Answers1

0

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106