bhylu.com

Advertisements

Async Fetch API

Fetch returns a promise for a response. Check response.ok before parsing data from a real HTTP endpoint.

Where to run this

This example uses the JavaScript console playground. Select Run to execute it; the example does not run on this lesson page.

A practical example

JavaScript

const response = new Response('{"places":12}', {status: 200});
if (!response.ok) throw new Error("Request failed");
const data = await response.json();
console.log(data.places);

What happens

The offline response example yields 12. A real request would obtain the Response from fetch.