ES2017 async/await with fetch in Redux (No Callback Hell anymore)

Shahjada Talukdar
2 min readMar 29, 2018

--

When we need to use third party API or any REST API in our web app, we need to wait for the response coming from the server.
Then in the success callback , we use that data and do other operations.And if we have more REST calls, we all know that it could end up being a Callback Hell

ES2017 async/await

But if we use ES2017 async/await syntax , we can write our code as clean as possible with minimum lines of code.

Basic example of async/await is like below-

here var result = await resolveAfter2Seconds(); will wait to resolve the Promise and assign the returned data to `result` variable.
It seems like its executing the code line by line though it has asynchronous operation , which is awesome!

As of now , we know basic of async/wait , now we will use this inside redux ActionCreator. But first we will see how the code looks like without using async/await.
So our action creator code is –

So here ^ is our action creator named `getSpeakers` which calls one REST API endpoint and then dispatch the speakers to the redux store.Here we can see we need to chain with `then`, `catch` etc which make the code a bit messy and hard to understand.

Now we will use async/await with fetch and will make our code good looking

Here , we have added try/catch so that if any error happens, we can catch and take our decision what we want to do. Here in this case , I have just thrown the error, but we can dispatch another FAILURE action.
Ah , that made our code smaller,cleaner and easy to understand!

Cheers!

Originally published at shahjada.me on March 29, 2018.

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

--

--

Shahjada Talukdar
Shahjada Talukdar

Written by Shahjada Talukdar

Senior Software Engineer @eBay. Tech enthusiast, loves JS + few other languages. Keen to learn about Software Engineering/Architecture.

No responses yet

Write a response