-3

JavaScript noobie here. Lacking knowledge of an important design pattern.

this.getEventData(); < How can I call that function after the promise is resolved? So then I can remove the noobie setTimeout ?

  public onInit(): Promise<void> {
    return super.onInit().then(_ => {
      new Promise<void>((resolve: () => void, reject: (error: any) => void): void => {
        this.context.aadHttpClientFactory
          .getClient(APIAppRegID)
          .then((client: AadHttpClient): void => {
            this.httpClient = client;
            resolve();
          }, err => reject(err));
      });
      setTimeout(() => {
        this.getEventData();
      }, 1500);
    });
  }
BennKingy
  • 1,265
  • 1
  • 18
  • 43
  • What does _"after the promise"_ mean? After the promise is resolved? The function is called after the promise is created. – jabaa Dec 01 '21 at 16:07
  • @jabaa Yes thats it – BennKingy Dec 01 '21 at 16:08
  • I'd recommend that you learn how promises work by reading ["Using Promises"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) on MDN. – zzzzBov Dec 01 '21 at 16:08
  • Why do you even create a `new Promise`? You are not using it. You can remove the whole promise part of the code. – jabaa Dec 01 '21 at 16:09

2 Answers2

1

The promise doesn't make any sense. You are not using it. You can remove it:

public onInit(): Promise<void> {
  return super.onInit().then(_ => {
    this.context.aadHttpClientFactory
      .getClient(APIAppRegID)
      .then((client: AadHttpClient): void => {
        this.httpClient = client;
        this.getEventData();
      });
  });
}
jabaa
  • 5,844
  • 3
  • 9
  • 30
1

async/await version :

async onInit(): Promise<void> {
  await super.onInit();
  this.httpClient = await this.context.aadHttpClientFactory.getClient(APIAppRegID);
  this.getEventData();
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63