DEV Community

منصور
منصور

Posted on

Master Async/Await: How to Write Cleaner and Faster JavaScript

How to Write Cleaner and Faster JavaScript

As JavaScript developers, we deal with asynchronous operations every single day—whether it's fetching data from an API, reading files, or talking to a database.

For years, we used callbacks (and suffered in Callback Hell), then we moved to Promises. Today, async/await is the gold standard. But are you using it efficiently, or are you accidentally slowing down your application?

In this post, we’ll look at how to avoid common pitfalls and write cleaner, faster async code.


1. The Common Mistake: The "Async/Await Ferry"

Look at this common pattern. We need to fetch user data and a list of products:

async function NewbieWay() {
  const user = await fetchUserData(); // Takes 2 seconds
  const products = await fetchProducts(); // Takes 2 seconds

  return { user, products };
}
Enter fullscreen mode Exit fullscreen mode

Why this is bad:

The code looks clean, but it runs sequentially. fetchProducts will not start until fetchUserData is completely finished. The total execution time is 4 seconds.

Since these two API calls do not depend on each other, waiting for the first one to finish is a waste of time.


2. The Solution: Parallel Execution with Promise.all

To speed things up, we should start both operations at the same time and wait for both to finish together.

async function ProWay() {
  // Start both requests in parallel
  const userPromise = fetchUserData(); 
  const productsPromise = fetchProducts();

  // Wait for both to resolve
  const [user, products] = await Promise.all([userPromise, productsPromise]);

  return { user, products };
}
Enter fullscreen mode Exit fullscreen mode

Why this is awesome:

Both requests are sent at the exact same moment. The total execution time drops from 4 seconds to just 2 seconds. You just doubled your app's performance with a simple tweak!


3. Don't Forget Error Handling

When using Promise.all, if one promise fails, the whole thing rejects. Always wrap your code in a try/catch block to handle errors gracefully.

async function SafeAndFast() {
  try {
    const [user, products] = await Promise.all([
      fetchUserData(),
      fetchProducts()
    ]);
    return { user, products };
  } catch (error) {
    console.error("Failed to fetch data:", error);
    // Handle error (e.g., show a notification to the user)
  }
}
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

async/await makes JavaScript code look synchronous and easy to read, but don't forget the asynchronous power underneath.

  • Use standard await when task B needs data from task A.
  • Use Promise.all when tasks are independent.

What is your favorite way to handle async operations in JavaScript? Let me know in the comments below! 🚀

javascript #webdev #programming #tutorial

Top comments (0)