Optimizing Async/Await for Performance and User Experience

Optimizing Async/Await for Performance and User Experience

Whenever I am coding, I think to myself, "Is there a better way?" or "Should I be using this here?" Well, I guess we all have these kinds of thoughts. Because of that, I decided to look for some answers.

I started looking into performance and realized that sometimes we use async/await by default, without taking much time to think through, for example:

const getUserData = async () => {
  const response = await fetch('https://avatar.iran.liara.run/public');
  
  // Convert the response to a blob
  const blob = await response.blob();
  
  // Create an object URL for the blob
  const imageUrl = URL.createObjectURL(blob);
  
  // Set the image URL to the <img> element
  const imgElement = document.getElementById("user-picture");
  imgElement.src = imageUrl;
  
  // Get our user's general data
  const data = await fetch('https://randomuser.me/api/');
  const { results } = await data.json();
    
  const user = results[0];
  // Set user details (except the picture)
  document.getElementById("user-name").textContent = `${user.name.title} ${user.name.first} ${user.name.last}`;
  document.getElementById("user-email").textContent = user.email;
  document.getElementById("user-phone").textContent = user.phone;
  document.getElementById("user-location").textContent = `${user.location.street.number} ${user.location.street.name}, ${user.location.city}, ${user.location.state}, ${user.location.country}`;
};
        

Breaking Down the Code

First, we fetch the avatar image, convert the response to a blob, create an object URL for it, and set it to the <img> element. After setting the image, we then fetch the user’s data, convert it to JSON, extract the results, and update the UI with the user’s details.

This code works correctly, but it could run faster. You can check it out for yourself: Async/Await Slow Method.


Making It Faster

What if we could optimize it? Let's try changing how we fetch the data:

const getUserDataFast = async () => {
  const [res, data] = await Promise.all([
    fetch('https://avatar.iran.liara.run/public'), 
    fetch('https://randomuser.me/api/')
  ]);

  const [blob, { results }] = await Promise.all([res.blob(), data.json()]);
  
  // Create an object URL for the blob
  const imageUrl = URL.createObjectURL(blob);
  
  // Set the image URL to the <img> element
  const imgElement = document.getElementById("user-picture");
  imgElement.src = imageUrl;
    
  const user = results[0];
  // Set user details (except the picture)
  document.getElementById("user-name").textContent = `${user.name.title} ${user.name.first} ${user.name.last}`;
  document.getElementById("user-email").textContent = user.email;
  document.getElementById("user-phone").textContent = user.phone;
  document.getElementById("user-location").textContent = `${user.location.street.number} ${user.location.street.name}, ${user.location.city}, ${user.location.state}, ${user.location.country}`;
};
        

Here, we're doing the same thing as before but with one slight change: instead of waiting for each fetch to complete before starting the next, we use Promise.all to run both fetches in parallel. Then, we use Promise.all again to process the responses simultaneously.

This small change significantly speeds up data retrieval. Try it yourself: Async/Await Fast Method.


Improving User Experience with a Skeleton Loader

Now, let’s imagine a scenario where the image takes a long time to load. A user waiting on a blank screen might feel frustrated or think something went wrong, leading to unnecessary refreshes.

To improve the experience, we can use a skeleton loader—a placeholder that visually indicates content is loading. This helps reduce perceived wait time and makes the delay feel more natural.

Here’s an example of a skeleton loader in action: Async/Await Skeleton Loading Method.

I've added a timer so you can see how long the process takes. Keep in mind that a skeleton loader doesn’t make loading faster—it simply makes the wait feel more manageable.


Final Thoughts

Optimizing async/await isn’t just about performance—it’s about user experience. Running async operations in parallel and using loading indicators can make applications feel much smoother and more responsive. Small changes like these can make a big difference!

要查看或添加评论,请登录

Mauro Nunes的更多文章

社区洞察

其他会员也浏览了