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.