Async JavaScript
Coordinate promises, async functions, fetch requests, cancellation, and failures.
Network requests, timers, and many browser APIs finish later. Promises represent that future result; async and await let code describe the sequence directly.
Await a promise
async function loadCourses() {
const response = await fetch("/api/courses");
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
}
fetch resolves even for HTTP errors such as 404 or 500, so check response.ok. Parsing JSON is also asynchronous.
Handle loading and failure
async function showCourses() {
setStatus("loading");
try {
const courses = await loadCourses();
renderCourses(courses);
setStatus("ready");
} catch (error) {
console.error(error);
setStatus("error");
}
}
Model loading, empty, success, and failure states. A caught error should lead to useful feedback or recovery, not disappear silently.
Run independent work together
const [profile, progress] = await Promise.all([
fetchProfile(),
fetchProgress(),
]);
Use Promise.all when all operations are required and independent. Cancel stale fetches with AbortController when a view changes or a new search replaces the old one.
Keep this
Check HTTP status, represent every UI state, run independent work concurrently, and surface failures intentionally.