Converting your Callback Functions into Async/Await Functions in under 3 minutes! (React 16)

Know It All
30 followers
3 Video Views·Oct 22, 2022
How often do you run into this situation?
You have an asynchronous request, so like a fetch request,
and you use this kind of syntax here,
where it's .then, .then, .catch.
Usually, you know, for situations like this
where I'm just trying to get one kind of price,
it works well.
But never ever do you ever just leave at this situation.
It always ends up with you needing to use,
you know, some sort of variable you get from this request,
and then you make another fetch request right here
to some other sort of API,
and then you get this kind of callback hell
that looks like this, where it's just like a Hadouken.
And we're all guilty of it.
It looks horrible, and it's even worse to debug.
So that's why I love asynchronous,
or sorry, the async await syntax for this kind of thing.
So here's what I'm going to do here.
I'm just going to comment this out.
As you can see, we just have a basic React application.
It just gets the price of a Bitcoin on page load.
So yeah, we're going to be using the useEffect hook
that's in, you know, React 16.
Really do love React 16.
It kind of just changes everything
from what I'm used to in React, but kind of in a good way.
So here's what I'm going to do.
I'm going to do a async function,
and I'm just going to call this getBitcoinPrice.
Cool, and then let's just do let response
is equal to async fetch.
And then, you know, because we are lazy devs,
we're just going to do this.
Copy the exact same code, right?
There we go.
And then response.
I'm just going to then assign this to the response.json,
which is, this is all part of the fetch API.
So, you know, this could really be anything.
If you're using Axios,
I'm pretty sure it's response.data, but yeah.
And then we'll also use the useState hook as well
to do setCoinPrice to, what was it again?
It was this right here, bpiUSD.rate.
So response, there we go.
Perfect, and see if it works.
Oh, sorry, got to call that function now.
GetBitcoinPrice, perfect.
And then does it work?
Yeah, perfect.
Yeah, there we go.
And just like that, you get this kind of easier to read code
that doesn't fall into this callback hell
that looks like this.
It just is kind of a linear process,
even though it's still doing all that asynchronous requests
that we are used to when working with a React application.
