01 / 20

Async/Await in
JavaScript

Master the modern syntax for asynchronous programming: write non-blocking code that reads like synchronous, step-by-step logic.

JavaScript

What Is Asynchronous Code?

JavaScript runs on a single thread: it can only do one thing at a time. When your program needs to fetch data from a server, read a file, or wait for a timer, it cannot freeze the entire page while waiting. Asynchronous code lets JavaScript start a task, move on to other work, and come back when the result is ready.

The Evolution of Async Patterns

Callbacks Nested, hard to read Promises .then() chains Async/Await Reads like sync ES5 ES6 (2015) ES2017

JavaScript async patterns evolved from tangled callbacks to chainable Promises, and finally to async/await: syntactic sugar over Promises that makes asynchronous code look and behave like synchronous code.

Quick Recap: Promises

A Promise is an object that represents a value that may not exist yet. It has three states:

Pending
The operation is still running. No result yet.
Fulfilled
The operation succeeded and produced a value.
Rejected
The operation failed and produced an error.

The async Keyword

Placing async before a function declaration does two things:

1
Wraps the return value in a Promise automatically. If the function returns 42, callers receive Promise.resolve(42).
2
Enables the await keyword inside the function body. Without async, using await is a syntax error.
async function greet() { return "Hello!"; } greet().then(msg => console.log(msg)); // "Hello!"

The await Keyword

await pauses execution of the async function until the Promise it is waiting on settles. The resolved value is returned directly, so you can assign it to a variable just like synchronous code.

async function fetchUser() { const response = await fetch("/api/user"); const data = await response.json(); return data; }

Under the Hood: Execution Flow

Call Stack fetchUser() runs Hits await → pauses Browser / Runtime fetch() in progress Network request... Response received ✓ Microtask Queue Resumes with value Meanwhile... Other code runs

.then() vs async/await

// Promise .then() chain fetch("/api/user") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
// Async/Await equivalent async function loadUser() { try { const res = await fetch("/api/user"); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } }

Error Handling: try/catch

When a Promise rejects inside an async function, it throws just like a regular error. Wrap your await calls in try/catch to handle failures gracefully.

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

How to Apply Async/Await

1
Mark the function as async. Add the async keyword before your function declaration or expression.
2
Identify the Promises. Find each asynchronous call that returns a Promise (fetch, database queries, timers, etc.).
3
Add await before each Promise. Assign the result to a variable. Code below will wait for the value.
4
Wrap in try/catch. Handle any rejected Promises inside the catch block.
5
Return the result. The caller receives a Promise that resolves with your return value.

Example 1: Basic Fetch

Goal: fetch a user object from an API and display the name.

async function showUserName() { try { const res = await fetch("https://api.example.com/user/1"); const user = await res.json(); document.getElementById("name").textContent = user.name; } catch (err) { console.error("Could not load user", err); } } showUserName();

Example 2: Sequential vs Parallel

// Sequential: total time = timeA + timeB const a = await fetchA(); // waits 2s const b = await fetchB(); // waits 2s after A // Total: ~4s
// Parallel: total time = max(timeA, timeB) const [a, b] = await Promise.all([ fetchA(), fetchB() ]); // Total: ~2s

Example 3: Arrow Functions & Loops

// Arrow function syntax const getPost = async (id) => { const res = await fetch(`/api/posts/${id}`); return res.json(); }; // Awaiting inside a for...of loop (sequential) async function printPosts(ids) { for (const id of ids) { const post = await getPost(id); console.log(post.title); } }

Common Mistakes

✕ Forgetting async
Using await in a regular function causes a SyntaxError. Always mark the function as async.
✕ Forgetting await
Omitting await gives you a Promise object instead of the resolved value. Your variable holds [object Promise].
✕ No Error Handling
Unhandled rejections crash silently. Always wrap await calls in try/catch or attach a .catch() to the returned Promise.
✕ Unnecessary Sequential
Awaiting independent Promises one-by-one wastes time. Use Promise.all() for parallel execution.

Comparison Summary

Callbacks .then() Chains Async/Await
Readability Poor (nesting) Moderate Excellent
Error Handling Manual checks .catch() try/catch
Debugging Hard Medium Easy
Sequential Flow Pyramid of doom Flat chains Line by line
Parallel Manual Promise.all() Promise.all()
Return Value None (callback) Promise Promise

Question 1 of 5

What does an async function always return?

Question 2 of 5

What happens if you use await inside a function that is not marked as async?

Question 3 of 5

Which approach runs two independent async operations in parallel?

Question 4 of 5

How should you handle a rejected Promise inside an async function?

Question 5 of 5

What value does the variable result hold after this code runs?

async function demo() { return 10; } const result = demo();