0

I need help with how I can return a string from a SP PnP js request?

I want to display the string displayName in the console log on the last line. The result.Title is a string.

public static GetUserDisplayNameById(Id: number) {
    return pnp.sp.site.rootWeb
        .getUserById(Id)
        .select("Title")
        .get()
        .then(result => {
            return result.Title;
        });
}

let UserDisplayName = Utility.GetUserDisplayNameById(13);
console.log(UserDisplayName);

But this is what gets displayed in the console:

Promise {<pending>}
{
    [[PromiseStatus]]: "resolved",
    [[PromiseValue]]: "Saad Humayun"
}
0

GetUserDisplayNameById returns Promise so you have to use .then().

public static GetUserDisplayNameById(Id: number) {
    return pnp.sp.site.rootWeb
        .getUserById(Id)
        .select("Title")
        .get()
        .then(result => {
            return result.Title;
        });
}

Utility.GetUserDisplayNameById(13).then(UserDisplayName => {
    console.log(UserDisplayName);
});

Or you can convert it to async/await pattern.

public static async GetUserDisplayNameById(Id: number) {
    const result = await pnp.sp.site.rootWeb
        .getUserById(Id)
        .select("Title")
        .get();
    return result.Title;
}

const UserDisplayName = await Utility.GetUserDisplayNameById(13);
console.log(UserDisplayName);
  • Thanks, async/await pattern solved my problem. – SaadRH Feb 28 at 11:54

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.