Using Fetch with async/await
Last updated: August 24, 2022.
A Fetch request made with async/await syntax avoids unnecessary nesting and allows promises to be handled with synchronous-looking code.
Table of contents
Fetch with promises syntax
Below is an example GET request made using the Fetch API, which returns a promise. The result is handled using the native promise methods .then
and .catch
:
function getRequest(url) {
return fetch(url)
.then((res) => {
if (res.ok) { // Checks server response (if there is one)
return res.json();
} else {
throw new Error("Bad response");
}
});
}
function getData(url) {
getRequest(url)
.then(data => {
console.log(data); // the data
})
.catch(err => console.log(err)); // Catch handles an error
}
getData('https://example-endpoint.com/api');
This way of handling a Fetch request involves some nesting within the promise methods and unfamiliar, non-synchronous looking code.
Fetch using async/await syntax
Async/await provides an alternative syntax for handling the result of a Fetch request and other promise-based methods. The Fetch request is rewritten using this syntax below.
Functions are prepended by the keyword async
, which enables the use of the keyword await
inside them. Any process that returns a promise is prepended by the keyword await
, which halts execution of the code below it until the promise is resolved or rejected. Errors are handled using try...catch
syntax.
async function getRequest(url) {
const res = await fetch(url);
if (res.ok) {
return res.json();
} else {
throw new Error("Bad response");
}
}
async function getData(url) {
try {
const data = await getRequest(url);
console.log(data);
} catch(e) {
console.log(e);
}
}
getData('https://reqres.in/api/users');
Now, the worst of the nesting has been removed, and the syntax looks much more like regular, synchronous code.
Under the hood, though, async/await still works with promises and the functionality is the same!
You can learn more about promises and async/await in our free tutorial on asynchronous JavaScript.
Related links
- OpenJavaScript: Asynchronous JavaScript: A Complete Tutorial
- OpenJavaScript: Using fetch to make GET, POST, PUT and DELETE requests
- MDN Web Docs: Async function