Skip to main content
Frontend tutorial

7.2. Fetch using then

The same request can be written without await, as a chain of then calls. Each then gets what the previous one returned:

getRamps(): Promise<Ramp[]> {
return fetch(BASE_URL + 'RAMPS.json')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}

return response.json() as Promise<RampResponse[]>;
})
.then(json => json.map(r => new Ramp(r.ramp_id, r.description)));
}

Watch the two returns: return response.json() passes the JSON to the next then, and return fetch(...) gives the whole chain to the store. Forget either and the chain breaks. There is no async this time: the chain is already a promise.

Which one is better? The one you read more easily. In ShippingBoard you'll write one of each.

Need a hint?
  • Without the return in the first then, the next one gets undefined.

The preview shows the same seven ramps. That's the point: one request, two ways to write it.

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-07-02-then-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
07-02-then
cd 07-02-then
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./07-02-then-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…