Question

Im trying to use a get call through the MsGraphClient in a synchronous manner, but it doesn't seem to be working for me:

public getDirectReports = async (manager): Promise<any[]> => {
console.info("** 2");
let dirReports;
return await this.graphClient
  .api(`users/${manager.email}/directReports`)
  .version("v1.0")
  .get(async (error, result: any, rawResponse?: any) => {
    console.info("** 3 ");
    return dirReports;
  });
};

export const getDirectReports = manager => async () => {
  console.info("** 1");
  let directReports = await this.getDirectReports(manager);
  console.info("** 4");
};

Frustratingly, the console.info output comes like: ** 1 ** 2 ** 4 ** 3

Meaning my code continues before the "direct reports" values have been returned by the Graph.

I created the graphClient in my SPfx webparts onInit, using:

this.graphClient = await this.context.msGraphClientFactory.getClient();

How can I make the code await the completion of the graphClient's get() call??

Thanks!!

Was it helpful?

Solution

Changing the function to return a resolved promise works as expected:

public getDirectReports = async (manager): Promise<any[]> => {
    console.info(`** 2 - /me/directReports`);
    return new Promise<any[]>((resolve, reject) => {
      this.graphClientFactory
        .api(`/me/directReports`)
        .version("v1.0")
        .get(async (error, result: any, rawResponse?: any) => {
          console.info("** 3");
          resolve(result);
        });
    });
  };

OTHER TIPS

An async from function needs to return a Promise, then resolve that Promise. Thankfully, React makes things a little easier for you. If you return a Promise, then later in your function body return a value, React resolves the Promise with your returned data.

If you return await *somePromise*, you don't actually return the Promise, but the result that you are awaiting. This would be fine if the calling function wasn't expecting a Promise. Try this:

public getDirectReports = async (manager): Promise<any[]> => {
    console.info("** 2");

    return this.graphClient
      .api(`users/${manager.email}/directReports`)
      .version("v1.0")
      .get(async (error, result: any, rawResponse?: any) => {
        console.info("** 3 ");
        return result;
    });
};
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top