This YouTube video was created by Steve Griffith.

The Fetch APIopen in new window is a replacement for the older XMLHttpRequestopen in new window and can be used to make Ajax requests. With a fetch request, the Fetch API will return a response in the form of a JavaScript Promiseopen in new window.

Basic Fetch Request

In many cases, the basic fetch request, relying on the default setting, can be sufficient. The following example is a basic fetch request that returns JSON data.

      .then(response => response.json())
      .then(json => document.write(JSON.stringify(json)))

Using Async and Await

An asyncopen in new window function, in conjunction with the await keyword, enables asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need for chaining. Async functions can provide an alternative syntax for working with the fetch.

(async function fetchData () {
  const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
  const json = await response.json()