Async Functions
This page contains more detailed information on asynchronous functions in React.
If you're working in development your web app, you probably want components and pages to load as fast as possible. This is where asynchronous functions come into play. With these functions, you can make it so that your component is not waiting on a function to start and finish on mounting, unmounting, etc; making your component load faster.
Let's take a look at a code snippet of this before going into more detail.
Async Function Example
This code snippet is actually real code from this very website! For context, this is a function that makes a PATCH request to update an existing field in a database table entry.
const saveAccountName = async () => { try { // Just setting some data for the request. const data = { name: accountName } // Validating the request with a token. // Don't worry about this part if you're not familiar. // This is just to further secure requests between the frontend and backend. const user = auth.currentUser; // Waiting for a response from user.getIdToken const token = user ? await user.getIdToken() : null; if (!token) { console.error("User is not authenticated."); return; } // Making the actual request. // Again, the await is to make sure we actually get a response; regardless of what the response may be. const response = await fetch(`https://bluebirddocumentationadmin.pythonanywhere.com/users/update/${uid}/`, { method: "PATCH", headers: { "Content-Type": "application/json", "auth-token": `Bearer ${token}`, }, body: JSON.stringify(data) }) // Handling the possible outcomes. if (response.ok) { alert("Account name changed successfully!") } else { alert("Failed to update account name.") } } catch (error) { alert("Failed to change account name: ", error) } }
Now, if I call this method on a button click for example, the user can go about doing other things on the page, and the alert will pop up whenever the response comes back from the server.
But there are some things to consider...
Depending on our business requirements, we may need to wait for a certain response or action to complete before proceeding; that's where await
comes into play. As you can see in the above code snippet, I use await
in two places: one for waiting for the authentication token to come from getIdToken()
, and another for waiting for the response to come back from the server from fetch()
.
Does using await
cause the UI to hang/freeze while waiting to resolve like synchronous functions might? No! While it does wait for whatever it is you've set it to wait for, it doesn't block the main thread. It's just like hitting the pause button on the asynchronous function itself.
What if other asynchronous functions need to wait on something to resolve from another asynchronous function? Let's say that you need to fetch some data from a database when a component first mounts, and you need to display it, or you need to used that fetched data in another function. This is when we need to utilize state; something like a loading state. Once that loading value is false, display the content, or trigger another function. While this still won't interrupt the main thread, you do need to consider if you want to cause a pause in the UI. Let's say I want to fetch profile details when the component mounts. I might want to display a loading animation by the time the loading state is false. Again, while the asynchronous functions don't cause any delays, it's important to know when you might need to purposely step in and put a delay.
Hopefully this is enough to get you started with asynchronous functions, and what to consider when using them! Please feel free to leave a comment below with any questions, comments, or concerns.
Part of: YouTube Channel