Refactoring with Async & Await

Joseph K Abe
2 min readAug 6, 2021

--

When I first started writing fetch methods I will be the first to admit that it was extremely confusing. They syntax didn’t look much like the javascript functions I know. Because of the asynchronous nature of a fetch I had to use .then() .then() .then() to make sure that the function was working in the order I wanted. Luckily using the keywords async and await make it possible to write functions that look (in my opinion) like javascript functions again. Lets take a look at an example of a fetch using .then()…

In this setMessage() function once we get to the fetch we would receive a promise and our computer would move down to the next line and come back and return the fetch later. This is why we are using .then() to tell the computer to run the fetch and then run this line. I can get pretty messy when there are multiple .then()s!

So when using async and await we can get away from this all together! Here is the same setMessage() function written with async and await…

All we have to do is declare our function as an async function with the keyword async! Then when we get to our fetch we make it a const that has the keyword await. What this does is it lets lets the computer know to wait for this to happen before going any further. Since now we don’t have to worry about our code running out of order we can write in a more traditional looking style!

Of course there are many other uses and positive reasons for using async and await but in my opinion, when coding style matters! I love the fact that now I can look at fetches in a more comfortable (in my humble opinion) javascript syntax!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response