
JavaScript Async/Await Syntax
β±οΈ Async/Await: JavaScript's Gift to Readability
Letβs be honest, the callback syntax for async code was a nightmare, and Promises with their .then() chains could still get messy fast.
Then came async/await. And everything changed.
But hereβs the thing: itβs not just syntactic sugar. It's a fundamental shift in how we write asynchronous code.
π In this cheatsheet, we'll cover:
β
async β marks a function as asynchronous, always returns a Promise
β
await β pauses execution until the Promise settles (without blocking the event loop)
β
try/catch β the familiar, intuitive way to handle errors (no more .catch() chaining)
#JavaScript #AsyncAwait #NodeJS #WebDevelopment #CodingTips #Programming #SoftwareEngineering #CleanCode #Frontend #Backend #TechLearning
async and await are syntactic sugar created to make Promises easier to read. They let you write asynchronous code that feels more like synchronous code.
async functions
async declares a function that always returns a Promise. If you return a non-promise value, it will be wrapped in Promise.resolve.
async function greet() {
return "Hello"; // Equivalent to: return Promise.resolve("Hello");
}
greet().then((message) => console.log(message)); // "Hello"If an async function throws an error, the returned Promise is rejected.
async function fail() {
throw new Error("Oops");
}
fail().catch((error) => console.error(error.message)); // "Oops"await keyword
await pauses the execution of an async function until the Promise resolves or rejects.
async function getUser(id) {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
}await only works inside async functions or at the top level of modules.
Error handling with try...catch
Wrap awaited calls in try...catch to handle errors:
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
console.log(user);
} catch (error) {
console.error("Failed to load user:", error.message);
}
}Use finally for cleanup logic.
async function fetchData() {
try {
const data = await fetch("/api/data");
return data;
} catch (error) {
console.error(error);
} finally {
console.log("Request finished");
}
}Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.