Promises - Fetch Method
fetch() makes an HTTP request and returns a promise for the response. It is built into browsers and into Node, and it replaces the older XMLHttpRequest, which used events and callbacks rather than promises.
The examples on this page request data from JSONPlaceholder, a free service that returns sample JSON for testing.
Getting JSON
Section titled “Getting JSON”Reading a JSON response takes two steps, because each step waits for something different. The promise from fetch() is fulfilled with a Response object as soon as the headers arrive, and the body may still be downloading. The response’s json() method then returns a second promise, which is fulfilled with the parsed body:
fetch('https://jsonplaceholder.typicode.com/todos/3') .then((response) => { console.log(response.status, response.headers.get('content-type')); return response.json(); }) .then((todo) => console.log(todo));This prints:
200 application/json; charset=utf-8{ userId: 1, id: 3, title: 'fugiat veniam minus', completed: false }Returning response.json() from the first then() makes the chain wait for the body. Response has similar methods for other formats, including text() and blob(), and the body can be read only once.
Checking for errors
Section titled “Checking for errors”The promise from fetch() is rejected only when no response arrives at all. A response with an error status, such as 404 or 500, still fulfils the promise, so the code has to check for it. The ok property is true for a status from 200 to 299:
fetch('https://jsonplaceholder.typicode.com/todos/9999') .then((response) => { if (!response.ok) { throw new Error(`Request failed with status ${response.status}`); } return response.json(); }) .then((todo) => console.log(todo.title)) .catch((error) => console.log(error.message));This prints:
Request failed with status 404Throwing inside the then() callback turns the bad status into a rejection, so one catch() handles it and network failures alike.
When the request cannot be made
Section titled “When the request cannot be made”A network failure, such as an unknown host, no connection or a request the browser blocks under its CORS rules, rejects the promise with a TypeError:
fetch('https://no-such-host.invalid/todos') .then((response) => console.log(response.status)) .catch((error) => console.log(error.name, '-', error.message));This prints, in Node:
TypeError - fetch failedBrowsers use their own wording for the message, such as “Failed to fetch” in Chrome.
Sending data
Section titled “Sending data”A second argument holds the request options. To send JSON, set the method, a Content-Type header and a body made with JSON.stringify():
const newTodo = { userId: 1, title: 'Water the plants', completed: false };
fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newTodo),}) .then((response) => response.json()) .then((saved) => console.log(saved));This prints:
{ userId: 1, title: 'Water the plants', completed: false, id: 201 }JSONPlaceholder pretends to save the to-do and sends it back with a new id. Other useful options include signal, which can cancel a request or give it a time limit with AbortSignal.timeout(). See Using the Fetch API on MDN for the full list.
Steve Griffith covers this topic in his video Fetch in Under Five.