How to return string from sp pnp js request?
-
05-02-2021 - |
Question
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"
}
Solution
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);
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange