JS Advanced
JavaScript Async/Await
Master asynchronous JavaScript with Promises, async/await, and fetching data from APIs.
JavaScript Asynchronous Programming
JavaScript is single-threaded but handles asynchronous operations through an event loop. Understanding async patterns is essential for modern web development.
Promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation.
States: pending → fulfilled or rejected
async/await
The async/await syntax is built on Promises and makes async code look synchronous. It's the modern way to handle async operations.
fetch API
The Fetch API provides a modern way to make HTTP requests. It returns a Promise.
Error Handling
Use try/catch with async/await to handle errors gracefully.
Example
javascript
// Promise basics
const fetchUser = (id) => new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: "Alice" });
else reject(new Error("Invalid ID"));
}, 1000);
});
// async/await
async function loadUser(id) {
try {
const user = await fetchUser(id);
console.log(user);
} catch (error) {
console.error("Error:", error.message);
}
}
// fetch API
async function getGitHubUser(username) {
try {
const response = await fetch(
`https://api.github.com/users/${username}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("Fetch failed:", error);
throw error;
}
}
// Promise.all - run in parallel
async function loadMultiple() {
const [users, posts] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json()),
]);
return { users, posts };
}Try it yourself — JAVASCRIPT