Async/Await into React……

July 16, 2017 0 Comments

Async/Await into React……



Magic is what Async/Await bring to the table for handling asynchronous requests. If we ponder more on asynchronous requests, they are requests made from our web page to some activity which is going to take it’s own time to respond. Sort of like a free willed activity, not caring for our application but responding at it’s own will at some later time. Our react component would be running in full energy .After mounting the described UI to the DOM, it goes ahead and asks the free willed activity : — -

Requesting the Free Willed Activity

And meanwhile our free willed activity is like

Unfortunately, our highly energetic react component will have to depend on promises. Thus, begins our journey of .then() & .then() & .then() & .then() oh wait .catch() wait what .throw() & finally .crazy().

But no worries now as Async/Await are here to rescue:

Let us first set up a local mock server which when requested will return some fake data like if the request is http://localhost:3000/HAPPY will return an array as [“PASSION”, “PEACE”, “COOL”]

So we are going to use a pre-built component network-vis which is based on vis.js to build another component which is going to fetch the fake data asynchronously and represent them as a set of nodes and edges. Each of those nodes when clicked can produce more nodes by fetching more data from server.

Package dependencies

Now our new component

So handleNodeClick is the method which is invoked every time a node is clicked in the Network component.We have defined the function to be asynchronous by adding the keyword async before the function definition. Inside the function definition we are using try/catch block. We are trying to to do something, but in the event that something is not triggered we log the failure to console in the catch block. The keyword await is used to wait for the activity which here is a promise of fetching data from remote server. So it seems as if the function execution stops here and waits for the promise fulfilled before continuing with the execution.

The above explanation is not what is actually happening on the inside. But to developer this explanation suffice. The function is asynchronous and it waits for a promise to complete and then continues with normal execution. Where did the callback? It is happening on the inside now I as a developer Don’t Care!!!. Our final output after clicking on HAPPY

Now click Peace

Git repo for the code is at

Please do leave your comments and if you think my understanding is wrong do help me out. I am just a beginner fiddling with magic, quite possible some of them may backfire.

Tag cloud