Loading...
Loading...
Async/await and Promise optimization guidelines. Use when writing, reviewing, or refactoring asynchronous code to eliminate waterfalls and maximize parallelism. Triggers on tasks involving data fetching, loaders, actions, or Promise handling.
npx skill4agent add sergiodxa/agent-skills frontend-async-best-practicesPromise.all()// Bad: 3 sequential round trips
const user = await fetchUser();
const posts = await fetchPosts();
const comments = await fetchComments();
// Good: 1 parallel round trip
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments(),
]);// Bad: always waits even when skipping
async function handle(skip: boolean) {
let data = await fetchData();
if (skip) return { skipped: true };
return process(data);
}
// Good: only waits when needed
async function handle(skip: boolean) {
if (skip) return { skipped: true };
let data = await fetchData();
return process(data);
}// Bad: profile waits for config unnecessarily
const [user, config] = await Promise.all([fetchUser(), fetchConfig()]);
const profile = await fetchProfile(user.id);
// Good: profile starts as soon as user resolves
const userPromise = fetchUser();
const profilePromise = userPromise.then((user) => fetchProfile(user.id));
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise,
]);// Bad: sequential execution
export async function loader() {
let session = await auth();
let config = await fetchConfig();
return { session, config };
}
// Good: parallel execution
export async function loader() {
let sessionPromise = auth();
let configPromise = fetchConfig();
const [session, config] = await Promise.all([sessionPromise, configPromise]);
return { session, config };
}// Bad: entire page blocked by data
async function Page() {
let data = await fetchData();
return (
<Layout>
<Content data={data} />
</Layout>
);
}
// Good: layout shows immediately, content streams in
function Page() {
return (
<Layout>
<Suspense fallback={<Skeleton />}>
<Content />
</Suspense>
</Layout>
);
}