DEV Community

Jason Mei
Jason Mei

Posted on

4 1

Refactoring ES6 Fetch with Async/Await

ES6 Fetch

Whether you've been using Javascript for a while, or a beginner just learning the basics of asynchronous functions in Javascript, you've most likely used the ES6 Fetch API to retrieve data from a URI. Here is an example of using fetch() to get user information from the Github API:

const getUser = name => {
 fetch(`https://api.github.com/users/${name}`)
  .then(response => response.json())
  .then(data => console.log(data))
};

//get user data
getUser('yourUsernameHere');

The above code isn't bad. It is fairly readable and it does function correctly. However, notice the .then() function, which supports a callback function for resolving the fetch function. You can imagine that as you start chaining more .then()'s, the code will get increasingly harder to read. This can lead into what is often referred to as "callback hell", or nested callbacks, and can easily lead to bad performance or bugs.

Refactor with async/await

ES8 brought about the async function and await keyword. Using async and await doesn't change how asynchronous functions operate. These features are just syntactical sugar that makes things more readable, and in turn makes handling the return of a Promise object more seamless. They also make asynchronous code look more like synchronous code. Below is the same fetch() call using async and await:

const getUser = async (name) => {
  let response = await fetch(`https://api.github.com/users/${name}`);
  let data = await response.json();
  return data;
}

//get user data
getUser('yourUsernameHere')
  .then(console.log(data));

Overall, this syntax is much easier to read and there is no longer a need for large .then() blocks. Keep in mind though, that in order to call a function using the await keyword, it must be within the async function. There's a lot more that can be covered in this topic, but I thought this would be a simple explanation to implementing async and await in your Javascript code.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay