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.

function getUser() {
fetch('https://api.github.com/users/octocat')
.then(response => response.json())
.then(data => {
console.log(`Name: ${data.name}`);
console.log(`Location: ${data.location}`);
})
.catch(error => console.error(error));
}

getUser();

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.

async function getUserAsync() {
try {
const response = await fetch('https://api.github.com/users/octocat');
const user = await response.json();
console.log(`Name: ${user.name}`);
console.log(`Location: ${user.location}`);
} catch (error) {
console.error(error);
}
}

getUserAsync();

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

--

--

ScriptyBeavers | JavaScript Tech community

Join ScriptyBeavers: A vibrant JS tech community connecting developers, sharing insights, and staying up-to-date with the latest trends!