Promises and fetch
Some operations, like a network request, take time and don't finish immediately. A Promise represents a value that will exist later, either successfully (resolved) or with an error (rejected). async/await lets you write that asynchronous code so it reads top-to-bottom, like ordinary synchronous code.
JavaScript
Reading it
new Promise((resolve) => { ... })creates a Promise that starts out pending. Callingresolve(value)(usually once some async work finishes) moves it to resolved with that value.awaitpauses the surroundingasyncfunction until the Promise resolves, then hands you the resolved value directly, no.then()callback needed.- Notice the console logs "loading…" before "loaded: ...",
awaitdoesn't freeze the whole page, it just pauses this function while other things could still happen.
fetch
With a real API you'd use fetch exactly the same way, it returns a Promise too:
const res = await fetch('/api/courses');
if (!res.ok) throw new Error('Request failed');
const courses = await res.json();
res.json() is itself asynchronous (parsing the response body takes a moment), so it needs its own await too.