学习库JavaScriptAsync JavaScript

Async JavaScript

Coordinate promises, async functions, fetch requests, cancellation, and failures.

更新于 适用于 ECMAScript 2026 and Fetch

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

courses.js
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

app.js
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

dashboard.js
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.

学习位置已保存在此设备上。