Skip to main content
← Back to Blog
2026-02-21 · 8 min readWeb DevelopmentUpdated Oct 30, 2026

Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide

A hands-on guide to JavaScript Promises. You build a small weather dashboard with fetch, check HTTP errors that fetch doesn't reject on, recover from failures with catch and finally, run requests in parallel with Promise.all and Promise.allSettled, and add a timeout with Promise.race and AbortSignal.timeout(). The code was run in order on Node.js 22 against a stubbed fetch.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
9 views
Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide

When a page waits on a server, a blocked thread means a frozen screen. When an automation waits on three APIs one after another, it is slower than it needs to be. This guide is for JavaScript developers who know the basics and want to handle asynchronous work with confidence. You'll build a small multi-city weather dashboard with Promises: fetching data, handling errors, running requests in parallel and adding timeouts.

This is part 11 of the Frontend & JavaScript Fundamentals series. It builds on the event loop, call stack and task queue, which explains when Promise callbacks run. This part shows how to use them.

Key takeaways

  • fetch() rejects only on network failures, not on 404 or 500. Check response.ok in your first .then().
  • Start independent requests together with Promise.all() (all or nothing) or Promise.allSettled() (keep partial results).
  • Promise.race() stops waiting but doesn't stop the request. Pass AbortSignal.timeout(ms) to fetch() to cancel it.

The synchronous trap

JavaScript runs your code on one thread, one line after another. If one line takes three seconds to compute, the next line waits three seconds. In a browser, the page can't respond while that happens.

Network calls don't work that way. fetch() starts the request and returns at once, and your code continues. You need a way to say "when the response arrives, do this". Callbacks were the first answer, but deep nesting made them hard to read (the well-known "callback hell"). Promises give you a flatter way to write the same logic.

Part 1: the anatomy of a Promise

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. That is MDN's definition. A Promise is always in one of three states:

  • Pending: the starting state. The operation hasn't finished.
  • Fulfilled: the operation succeeded, and the promise holds a value.
  • Rejected: the operation failed, and the promise holds a reason (usually an Error).

A promise that is fulfilled or rejected is settled. You attach your logic to the settled states with .then() and .catch().

You'll also hear "resolved". MDN notes that it isn't quite the same as "fulfilled": a resolved promise is locked to the outcome of another promise, so it can still be pending or end up rejected.

Part 2: basic data fetching

Start the dashboard. The native fetch() API returns a Promise, so you don't need the older XMLHttpRequest.

Here is a function that gets the weather for one city. It uses the OpenWeather current weather API. Notice the chain of .then() calls.

const API_KEY = 'YOUR_API_KEY'; // a free key from openweathermap.org
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather';

const getWeather = (city, { signal } = {}) => {
  console.log(`[Status] Fetching data for ${city}...`);
  // URLSearchParams encodes spaces and special characters ("New York")
  const params = new URLSearchParams({ q: city, appid: API_KEY, units: 'metric' });

  // fetch returns a Promise
  return fetch(`${BASE_URL}?${params}`, { signal })
    .then((response) => {
      // The first promise fulfills with the Response object.
      // Check the HTTP status yourself.
      if (!response.ok) {
        throw new Error(`HTTP Error! Status: ${response.status}`);
      }
      // response.json() also returns a Promise
      return response.json();
    })
    .then((data) => {
      // This runs once the JSON is parsed
      return {
        city: data.name,
        temp: data.main.temp,
        condition: data.weather[0].description,
      };
    });
};

// Usage
getWeather('Tokyo')
  .then((weather) => console.log(weather))
  .catch((error) => console.error('[Failed]', error.message));

Every code block in this post was run in order as one script on Node.js 22.23, 2026-10-30, with fetch replaced by a local stub that answers with delays and 404 or 500 statuses. The stub honours the abort signal, so the timeout example below really hit its TimeoutError branch. To call the real API, you need your own OpenWeather key in place of YOUR_API_KEY.

Keep API keys out of shipped frontend code

Any key in browser JavaScript is visible to every visitor. For a real dashboard, call your own backend and let it hold the key. Also note that OpenWeather marks requests by city name as deprecated: they still work, but its docs point to the Geocoding API and coordinates for new code.

Reading the chain

You didn't nest callbacks. You chained .then() calls, and each one gets what the previous one returned.

  1. fetch() starts the network request.
  2. The first .then() gets the raw HTTP response. You must check response.ok yourself. MDN says a fetch() promise only rejects when the request fails, such as on a network error, and does not reject on statuses like 404 or 504. Then response.json() reads and parses the body.
  3. The second .then() gets the parsed object and keeps only the fields the dashboard needs.

Each step hands a clean value to the next, so the chain reads like a small data pipeline.

Part 3: error handling

APIs fail. Rate limits get hit and networks drop. A rejection with no handler doesn't fix itself: the screen keeps waiting, or the error surfaces as an unhandled rejection.

In a promise chain, an error thrown in any step skips ahead to the nearest .catch(). Use that to turn failures into something the UI can show, and add .finally() for cleanup.

const resilientGetWeather = (city) => {
  const params = new URLSearchParams({ q: city, appid: API_KEY, units: 'metric' });

  return fetch(`${BASE_URL}?${params}`)
    .then((response) => {
      if (response.status === 404) {
        throw new Error(`City "${city}" not found.`);
      }
      if (response.status === 401) {
        throw new Error('Invalid API key.');
      }
      if (!response.ok) {
        throw new Error(`HTTP Error! Status: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => ({
      city: data.name,
      temp: data.main.temp,
    }))
    .catch((err) => {
      // Turn the error into a value the UI can render
      console.error(`[Log] Error processing ${city}:`, err.message);
      return { city, error: err.message };
    })
    .finally(() => {
      // Runs on success and failure: hide the loading spinner here
      console.log(`[Status] Request for ${city} finished.`);
    });
};

.finally() matters for UI state. Whether the request succeeds or fails, the "Loading..." spinner has to go. This is the one place that runs either way.

Fixed in this version

The earlier code put the city name straight into the URL, so "New York" sent an unencoded space. URLSearchParams now builds the query. The error handler also let statuses other than 401 and 404 (such as a 500) fall through to response.json(); it now checks response.ok as well.

Part 4: parallel requests with Promise.all()

Say the dashboard shows London, New York and Tokyo as soon as it loads. A first attempt often looks like this:

// Avoid: each request waits for the one before it
getWeather('London')
  .then((data1) => {
    return getWeather('New York').then((data2) => {
      return getWeather('Tokyo').then((data3) => {
        console.log('Serial results:', [data1, data2, data3]);
      });
    });
  })
  .catch((error) => console.error('[Failed]', error.message));

London must finish before New York starts. If each request took one second, the user would wait about three.

These requests don't depend on each other, so start them all at once and wait for the group with Promise.all():

const cities = ['London', 'New York', 'Tokyo', 'Singapore'];

const fetchDashboardData = (cityList) => {
  console.time('Dashboard Fetch');

  // map() starts every request right away and collects the promises
  const weatherPromises = cityList.map((city) => getWeather(city));

  return Promise.all(weatherPromises)
    .then((results) => {
      console.timeEnd('Dashboard Fetch');
      // results is in the same order as cityList
      console.log('All cities loaded:', results);
    })
    .catch((error) => {
      // If ONE promise rejects, Promise.all rejects
      console.error('One or more requests failed:', error.message);
    });
};

fetchDashboardData(cities);

Now the total wait is roughly the time of the slowest request, not the sum of all of them. MDN confirms that the results come back "in the order of the promises passed, regardless of completion order."

The all-or-nothing caveat

Promise.all() rejects as soon as any input rejects, with that first reason. If New York fails, you never see London's data from that call. MDN's Promise.all() page adds that rejecting "does not cancel the remaining operations": the other requests keep running, and their results are just ignored. On a dashboard, partial data is often better than none.

When you want every result, use Promise.allSettled(). It waits for all promises to settle and gives you an object per input with a status of "fulfilled" (plus value) or "rejected" (plus reason).

Promise.allSettled(cities.map((city) => getWeather(city))).then((results) => {
  results.forEach((result, i) => {
    if (result.status === 'fulfilled') {
      console.log('Loaded:', result.value);
    } else {
      console.error(`Failed: ${cities[i]}:`, result.reason.message);
    }
  });
});
Method Settles when Result When to use
Promise.all() All fulfill, or the first rejects Array of values in input order Every result is required
Promise.allSettled() All have settled Array of { status, value / reason } Partial results are useful
Promise.race() The first one settles That promise's value or reason First answer wins, simple timeouts
Promise.any() The first one fulfills, or all reject First value, or an AggregateError Any one healthy source is enough

Part 5: race conditions and timeouts

Sometimes a request hangs. After a few seconds you'd rather tell the user to try again. Promise.race() settles with whichever promise settles first, so you can race the request against a timer:

const timeout = (ms) => {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error('Request timed out')), ms);
  });
};

const fetchWithTimeout = (city, ms) => {
  return Promise.race([getWeather(city), timeout(ms)]);
};

// Usage: give up waiting after 2 seconds
fetchWithTimeout('Sydney', 2000)
  .then((data) => console.log('Data received:', data))
  .catch((err) => console.error(err.message));

This stops waiting, but it doesn't stop the request. MDN's Promise.race() page warns that one promise finishing doesn't cancel the other, and recommends the AbortController API for fetch. The simplest way is AbortSignal.timeout(), which returns a signal that aborts on its own after the given time:

getWeather('Sydney', { signal: AbortSignal.timeout(2000) })
  .then((data) => console.log('Data received:', data))
  .catch((err) => {
    if (err.name === 'TimeoutError') {
      console.error('Gave up after 2 seconds; the request was cancelled.');
    } else {
      console.error(err.message);
    }
  });

Because getWeather passes the signal to fetch(), the request is cancelled when time runs out. MDN says the signal aborts with a TimeoutError, so you can tell a timeout apart from other failures.

The builder's mindset

Promises are more than a way to avoid callbacks. They let you model parallel work, races and error paths in code that reads top to bottom.

When you build dashboards or automations:

  1. Use chaining to check and shape data as it arrives.
  2. Use Promise.all() or Promise.allSettled() to run independent work in parallel.
  3. Use AbortSignal.timeout() (or Promise.race() where cancelling doesn't matter) to cap how long you wait.

With this model in place, async/await is easy to pick up: await pauses an async function until a Promise settles. The next part, modern async patterns with async/await and generators, rewrites this dashboard in that style.

Frequently asked questions

Why doesn't fetch() reject on a 404?

To fetch(), a 404 is a successful exchange: the server answered. MDN says the promise only rejects when the request itself fails, such as on a network error. Check response.ok or response.status and throw your own error.

What is the difference between Promise.all() and Promise.allSettled()?

Promise.all() fulfills with every value, or rejects with the first error. Promise.allSettled() always waits for every promise and reports each outcome. Use allSettled() when some results are useful even if others fail.

Does Promise.race() cancel the slower promise?

No. MDN notes that the other operation keeps running and its result is ignored. To cancel a fetch(), pass an AbortSignal, for example AbortSignal.timeout(2000).

Are "resolved" and "fulfilled" the same thing?

Not exactly. "Fulfilled" means the operation succeeded. "Resolved" means the promise's fate is locked to another promise, which may still be pending or may reject. In everyday talk people often use them as if they were the same.

Should I use .then() or async/await?

Both work with the same Promises. async/await usually reads more naturally for step-by-step code, while .then() chains are handy for short pipelines. Knowing how Promises behave helps with either style.

Sources

Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.

  1. MDN: Promise
  2. MDN: Window.fetch()
  3. MDN: Promise.all()
  4. MDN: Promise.allSettled()
  5. MDN: Promise.race()
  6. MDN: Promise.any()
  7. MDN: AbortSignal.timeout()
  8. OpenWeather: Current weather data API
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.