Life before async/await
JavaScript runs on a single thread, so anything slow - a network call, a file read, a timer - has to happen asynchronously. Before async/await existed, chaining a few of these together meant nesting .then() calls, and that got hard to follow fast. Async/await mostly fixes that.
Declaring an async function
Just put async in front of function. From that point on the function always returns a Promise, even if all you wrote was return 42.
async function greet(name: string): Promise<string> {
return `Hello, ${name}`;
}
greet("Alice").then(console.log); // Hello, Alice
What await actually does
Inside an async function, await pauses that function until the Promise resolves, then hands you the resolved value directly. Anything written after the await waits until that settles.
async function fetchUser(id: string) {
const res = await fetch(`/api/users/${id}`);
const data = await res.json();
return data;
}
Handling failures with try/catch
If an awaited Promise rejects, it throws right there inside your async function - so a normal try/catch around your awaited calls handles it just fine.
async function fetchUser(id: string) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error("Failed to fetch user:", err);
return null;
}
}
Don't await things one at a time if you don't have to
Awaiting independent calls sequentially just wastes time. Use Promise.all to fire them off together and wait for all of them at once.
const [user, posts] = await Promise.all([ fetchUser(userId), fetchPosts(userId), ]);
Comments
Loading comments...
Related Articles
Taming Slow MongoDB Aggregation Pipelines in Production
An aggregation pipeline that returns instantly on your 500-document local dataset can crawl once it hits a few million real documents. Here's how to actually find and fix the stage that's costing you.
Read ArticleBuilding a Sliding-Window Rate Limiter for Node.js APIs with Redis
Fixed-window rate limiting looks fine in a demo and then lets through double the traffic right at the window boundary. Here's the sliding-window-counter approach that fixes that, built directly on Redis.
Read ArticleMulti-Tenant Data Isolation: Shared Schema vs Separate Databases
Every multi-tenant SaaS eventually has to answer one question honestly: how do you stop one customer from ever seeing another customer's data? Here's how the three common isolation strategies actually compare in practice.
Read Article