JavaScript

JavaScript Promises and Async/Await

The Problem: Asynchronous Code

Operations like fetching data from a server don’t finish instantly. JavaScript needs a way to say “run this code once the result is ready” without freezing the whole page.

Promises

A Promise represents a value that will exist in the future. It has three states: pending, fulfilled, or rejected.

function fetchUser() { return new Promise((resolve, reject) => { setTimeout(() => resolve({ name: "Asha" }), 1000); }); } fetchUser().then(user => console.log(user.name));

async/await: Cleaner Syntax

async/await is syntax sugar over Promises that lets asynchronous code read like normal, synchronous code.

async function loadUser() { const user = await fetchUser(); console.log(user.name); } loadUser();

Handling Errors

Wrap awaited calls in try/catch instead of chaining .catch():

async function loadUser() { try { const user = await fetchUser(); console.log(user.name); } catch (err) { console.error("Failed to load user:", err); } }

Running Multiple Promises in Parallel

Awaiting one call at a time is slow if the calls don’t depend on each other. Use Promise.all instead:

async function loadDashboard() { const [user, orders] = await Promise.all([ fetchUser(), fetchOrders() ]); }

Common Mistake

Forgetting await means you’re working with the Promise object itself, not its resolved value — a very frequent beginner bug.

Practice Exercise

Write an async function that fetches data from two mock functions in parallel and logs both results once both are done.

Leave a Reply

Your email address will not be published. Required fields are marked *