Modern JavaScript Essentials

Lesson 3 of 6

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. Calling resolve(value) (usually once some async work finishes) moves it to resolved with that value.
  • await pauses the surrounding async function until the Promise resolves, then hands you the resolved value directly, no .then() callback needed.
  • Notice the console logs "loading…" before "loaded: ...", await doesn'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.

📝 Async Quiz

Passing score: 70%
  1. 1.Inside an async function you pause for a Promise with the ____ keyword.

  2. 2.What does fetch() return?