JavaScript Async/Await Cheatsheet
ā±ļø JavaScript Async/Await Cheatsheet
async and await are syntactic sugar over Promises that make asynchronous code easier to read and write.
ā async functions ā await keyword ā Error handling with try...catch
#javascript #async #await #promises #errorhandling #webdev #frontend #coding #tips
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.