Technology

Async/Await in JavaScript, Without the Confusion

Beginner 15 min read VisTechie Team Technology
1 views

Life before async/await

JavaScript runs on a single thread, so anything slow - a network call, a file read, a timer - has to happen asynchronously. Before async/await existed, chaining a few of these together meant nesting .then() calls, and that got hard to follow fast. Async/await mostly fixes that.

Declaring an async function

Just put async in front of function. From that point on the function always returns a Promise, even if all you wrote was return 42.

async function greet(name: string): Promise<string> {
  return `Hello, ${name}`;
}

greet("Alice").then(console.log); // Hello, Alice

What await actually does

Inside an async function, await pauses that function until the Promise resolves, then hands you the resolved value directly. Anything written after the await waits until that settles.

async function fetchUser(id: string) {
  const res = await fetch(`/api/users/${id}`);
  const data = await res.json();
  return data;
}

Handling failures with try/catch

If an awaited Promise rejects, it throws right there inside your async function - so a normal try/catch around your awaited calls handles it just fine.

async function fetchUser(id: string) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error("Failed to fetch user:", err);
    return null;
  }
}

Don't await things one at a time if you don't have to

Awaiting independent calls sequentially just wastes time. Use Promise.all to fire them off together and wait for all of them at once.

const [user, posts] = await Promise.all([
  fetchUser(userId),
  fetchPosts(userId),
]);
1 views

Comments

0/2000

Comments are reviewed before being published.

Loading comments...

Related Articles