Wait for the coffee, then continue
Day 53 of 149
👉 Full deep-dive with code examples
The Coffee Shop
With Promises:
- "I'll order coffee"
.then(() => wait for coffee).then(() => sit down).then(() => drink)
With Async/Await:
- Order coffee
- Wait for it
- Sit down
- Drink
Reads like normal steps! ☕
The Syntax
Before (Promises):
fetchUser()
.then((user) => fetchPosts(user.id))
.then((posts) => displayPosts(posts))
.catch((err) => console.error(err));
After (Async/Await):
async function loadDashboard() {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
displayPosts(posts);
}
Looks like regular code!
The Rules
-
asyncbefore a function = the function returns a Promise -
awaitbefore a Promise (or “thenable”) = "Pause this async function until it settles, then continue" -
awaitusually works insideasyncfunctions (and in some environments, at the top level)
Note: await makes code easier to read, but it doesn't automatically run work in parallel — it just waits at that line. Use patterns like Promise.all() when tasks are independent.
Error Handling
async function loadData() {
try {
const data = await fetchData();
return data;
} catch (error) {
console.error("Failed!", error);
}
}
Use try/catch just like regular code!
In One Sentence
Async/await makes asynchronous code easier to read by letting you write Promise-based logic in a step-by-step style.
🔗 Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)