How to Convert a JavaScript Function to an Asynchronous Function using async/await for Improved Performance

It is essential to know how to work with APIs in the modern world because everything is moving to the cloud.
One of the most well-known APIs is the GitHub API, which enables programmatic interaction between developers and GitHub.
The async and await keywords will be used to turn a JavaScript function that interacts with the GitHub API from synchronous to asynchronous in this article.

The original purpose is clear-cut.
A specific user was loaded from the GitHub API, the response was parsed as JSON, and the user’s name and location were then recorded to the console.
However, because this function was synchronous, the program would pause before running the next line of code until the response had been received.
This could result in problems if the response is delayed and the program becomes unresponsive.

To solve this problem, we can convert the synchronous function into an asynchronous function using the async and await keywords. By using async and await, we can write code that looks synchronous, but actually runs asynchronously.

To convert the original function, we start by adding the async keyword to the function declaration. This tells JavaScript that the function is asynchronous and will return a Promise. Next, we use the await keyword to wait for the fetch call to complete. The await operator pauses the function execution until the Promise returned by the fetch call is settled.

Once the Promise is resolved, we can assign the response body to a variable using the await keyword again. Then we can parse the response body as JSON using the JSON method, which also returns a Promise. We can once again use the await keyword to wait for the Promise to settle and assign the resulting object to a variable.

Finally, we can log the user’s name and location to the console just like before. By converting the function to an asynchronous function, we have eliminated the potential for the program to become unresponsive while waiting for the response from the API.

As you can see, the asynchronous function looks much cleaner and easier to read compared to the original function. The try-catch block makes error handling much easier and the use of await makes the code flow more like synchronous code.

#JavaScript #async #await #GitHubAPI #asynchronousFunction #performanceImprovement #codeEfficiency #JavaScriptFunction



👋 Hi! I'm a nerdy developer passionate about tech and Node.js. Join me on Discord! 👉

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
kapil gupta

👋 Hi! I'm a nerdy developer passionate about tech and Node.js. Join me on Discord! 👉