sync-construction-async-property-ui-render-gate-pattern
Sync construction with async property pattern. Use when creating clients that need async initialization but must be exportable from modules and usable synchronously in UI components.
Install
mkdir -p .claude/skills/sync-construction-async-property-ui-render-gate-pattern && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4059" && unzip -o skill.zip -d .claude/skills/sync-construction-async-property-ui-render-gate-pattern && rm skill.zipInstalls to .claude/skills/sync-construction-async-property-ui-render-gate-pattern
About this skill
Sync Construction, Async Property
The initialization of the client is synchronous. The async work is stored as a property you can await, while passing the reference around.
When to Apply This Pattern
Use this when you have:
- Async client initialization (IndexedDB, server connection, file system)
- Module exports that need to be importable without
await - UI components that want sync access to the client
- SvelteKit apps where you want to gate rendering on readiness
Signals you're fighting async construction:
await getX()patterns everywhere- Top-level await complaints from bundlers
- Getter functions wrapping singleton access
- Components that can't import a client directly
The Problem
Async constructors can't be exported:
// This doesn't work
export const client = await createClient(); // Top-level await breaks bundlers
So you end up with getter patterns:
let client: Client | null = null;
export async function getClient() {
if (!client) {
client = await createClient();
}
return client;
}
// Every consumer must await
const client = await getClient();
Every call site needs await. You're passing promises around instead of objects.
The Pattern
Make construction synchronous. Attach async work to the object:
// client.ts
export const client = createClient();
// Sync access works immediately
client.save(data);
client.load(id);
// Await the async work when you need to
await client.whenSynced;
Construction returns immediately. The async initialization (loading from disk, connecting to servers) happens in the background and is tracked via whenSynced.
The UI Render Gate
In Svelte, gate once at the root using @epicenter/ui/spinner for the loading state and @epicenter/ui/empty for error recovery:
<!-- +layout.svelte -->
<script>
import * as Empty from '@epicenter/ui/empty';
import { Spinner } from '@epicenter/ui/spinner';
import TriangleAlertIcon from '@lucide/svelte/icons/triangle-alert';
import { client } from '$lib/client';
</script>
{#await client.whenSynced}
<Empty.Root class="flex-1">
<Empty.Media>
<Spinner class="size-5 text-muted-foreground" />
</Empty.Media>
<Empty.Title>Loading…</Empty.Title>
</Empty.Root>
{:then}
{@render children?.()}
{:catch}
<Empty.Root class="flex-1">
<Empty.Media>
<TriangleAlertIcon class="size-8 text-muted-foreground" />
</Empty.Media>
<Empty.Title>Failed to load</Empty.Title>
<Empty.Description>
Something went wrong during initialization. Try reloading.
</Empty.Description>
</Empty.Root>
The gate guarantees: by the time any child component's script runs, the async work is complete. Children use sync access without checking readiness.
Always include {:catch} — if the async seed fails (e.g. browser.windows.getAll throws), the user sees an actionable error instead of an infinite spinner.
Implementation
The withCapabilities() fluent builder attaches async work to a sync-constructed object:
function createClient() {
const state = initializeSyncState();
return {
save(data) {
/* sync method */
},
load(id) {
/* sync method */
},
withCapabilities({ persistence }) {
const whenSynced = persistence(state);
return Object.assign(this, { whenSynced });
},
};
}
// Usage
export const client = createClient().withCapabilities({
persistence: (state) => loadFromIndexedDB(state),
});
Before and After
| Aspect | Async Construction | Sync + whenSynced |
|---|---|---|
| Module export | Can't export directly | Export the object |
| Consumer code | await getX() everywhere | Direct import, sync use |
| UI integration | Awkward promise handling | Single {#await} gate |
| Type signature | Promise<X> | X with .whenSynced |
Real-World Example: y-indexeddb
The Yjs ecosystem uses this pattern everywhere:
const provider = new IndexeddbPersistence('my-db', doc);
// Constructor returns immediately
provider.on('update', handleUpdate); // Sync access works
await provider.whenSynced; // Wait when you need to
They never block construction. The async work is always deferred to a property you can await.
Alternate Pattern: Await in Every Method
Alternatively, you can skip the whenReady property entirely and hide the initialization await inside each method. The canonical example is idb:
const dbPromise = openDB('keyval-store', 1, { upgrade(db) { db.createObjectStore('keyval') } });
export async function get(key) { return (await dbPromise).get('keyval', key); }
export async function set(key, val) { return (await dbPromise).put('keyval', val, key); }
Use whenReady when your client has sync methods that depend on initialized state. Use await-in-every-method when every method is async anyway (like database access). See the idb await-in-every-method article for a deeper comparison.
Related Patterns
- Lazy Singleton — when you need race-condition-safe lazy initialization
- Don't Use Parallel Maps — attach state to instances instead of tracking separately
References
- Full article — detailed explanation with diagrams
- Comprehensive guide — 480-line deep dive with idb example
- idb await-in-every-method — the sibling pattern for purely async APIs
More by EpicenterHQ
View all skills by EpicenterHQ →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversUnlock AI-ready web data with Firecrawl: scrape any website, handle dynamic content, and automate web scraping for resea
Async browser automation server using GPT-4o for remote web navigation, extraction, and tasks. Ideal for Selenium softwa
Browser Use offers async browser automation with GPT-4o. Ideal for selenium software testing and browser automation stud
Shell Command lets you securely execute whitelisted shell commands on your system using powerful asyncio integration.
Enable real-time, secure chat via telegram bots. Telegram Communicator supports asynchronous messaging & private telegra
Connect real-world devices like Raspberry Pi using asynchronous serial interface and comms port for advanced IoT and rob
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.