2

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!!

1

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;
    });
};
| improve this answer | |
  • Hi - Thanks for the response! I changed the function as described (removing the awaits so it returns the promise) but I still get the same result: ** 1, **2, **4, **3. Ideally I want the "getDirectReports" to block and return the final result of the API calls. I use the same pattern for many other PnP-wrapped api calls, but it behaves differently for "msGraphClientFactory". Thanks!! – Nigel Witherdin Mar 19 at 20:47
1

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);
        });
    });
  };
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.