How to refactor deskStructure with async/await for better readability?
Yes! You can absolutely use async/await to make your deskStructure function more readable. The Structure Builder accepts functions that return promises, so you can use modern async/await syntax instead of chaining .then() calls.
Here's how you can refactor your code:
export default defineConfig({
// ... other config
plugins: [
structureTool({
structure: async (S) => {
try {
const { roles, name } = await userStore.getCurrentUser();
const roleNames = roles.map((r) => r.name);
if (roleNames.includes("administrator")) {
return S.list()
.title(`${name} — Website Admin Menu`)
.items([...deskItems, settingsMenu]);
}
if (roleNames.includes("editors")) {
editors.push(...deskItems);
}
return S.list().title("Website Menu").items(deskItems);
} catch (error) {
console.error(error);
return S.list().title("Empty or Faulty structure").items([]);
}
}
})
]
})The key changes:
- Make the structure function
asyncby adding theasynckeyword - Use
awaitinstead of.then()to unwrap the promise fromgetCurrentUser() - Replace
.catch()with atry/catchblock for error handling
This approach is much more readable and follows modern JavaScript patterns. The Structure Builder API supports both promise chains and async/await since it just expects a function that returns a promise or a synchronous return value.
You could also extract this into a separate function if you want to keep your config file cleaner:
async function createStructureForUser(S) {
try {
const { roles, name } = await userStore.getCurrentUser();
const roleNames = roles.map((r) => r.name);
if (roleNames.includes("administrator")) {
return S.list()
.title(`${name} — Website Admin Menu`)
.items([...deskItems, settingsMenu]);
}
if (roleNames.includes("editors")) {
editors.push(...deskItems);
}
return S.list().title("Website Menu").items(deskItems);
} catch (error) {
console.error(error);
return S.list().title("Empty or Faulty structure").items([]);
}
}
export default defineConfig({
plugins: [
structureTool({
structure: createStructureForUser
})
]
})Both approaches work equally well – choose whichever fits your code organization preferences better!
Show original thread7 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.