Fetch
This YouTube video was created by Steve Griffith.
The Fetch API is a replacement for the older XMLHttpRequest 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 Promise.
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.
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(json => document.write(JSON.stringify(json)))
Using Async and Await
An async
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()
document.write(JSON.stringify(json))
})()