JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Promises & Async/Await

javascript
mid
async

What are Promises in JavaScript and how do they work?

promises
async
asynchronous
callbacks
error-handling
Quick Answer

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, or rejected, and provides .then(), .catch(), and .finally() methods for handling results.

Detailed Explanation

Promises provide a cleaner way to handle asynchronous operations compared to callbacks.

Promise States:

  1. Pending: Initial state, operation not completed
  2. Fulfilled: Operation completed successfully
  3. Rejected: Operation failed

Key Methods:

  • .then(onFulfilled, onRejected): Handles success and optionally errors
  • .catch(onRejected): Handles errors (syntactic sugar for .then(null, fn))
  • .finally(onFinally): Runs regardless of outcome

Static Methods:

  • Promise.all(): Waits for all promises, fails if any fails
  • Promise.allSettled(): Waits for all, returns all results regardless of outcome
  • Promise.race(): Returns first settled promise
  • Promise.any(): Returns first fulfilled promise
  • Promise.resolve() / Promise.reject(): Create resolved/rejected promises
  • Promise.withResolvers() (ES2024): Returns {promise, resolve, reject} for deferred patterns
  • Promise.try() (ES2025): Wraps sync or async functions into a Promise chain safely

Code Examples

Creating and using PromisesJavaScript
// Creating a Promise
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true;
    if (success) {
      resolve({ data: 'Hello World' });
    } else {
      reject(new Error('Failed to fetch'));
    }
  }, 1000);
});

// Consuming a Promise
fetchData
  .then(result => {
    console.log(result.data); // 'Hello World'
    return result.data.toUpperCase();
  })
  .then(upperData => {
    console.log(upperData); // 'HELLO WORLD'
  })
  .catch(error => {
    console.error(error.message);
  })
  .finally(() => {
    console.log('Operation complete');
  });

Real-World Applications

Use Cases

API Data Fetching

Chaining HTTP requests with error handling using .then()/.catch() for sequential or parallel data loading

File Upload

Tracking upload progress and handling success or failure asynchronously with user feedback

Database Operations

Sequencing queries that depend on previous results, such as fetching a user then their posts

Mini Projects

Promise-based Retry

beginner

Build a retry wrapper that attempts a failing async operation N times with exponential backoff delay

Parallel Data Loader

intermediate

Fetch multiple API endpoints in parallel using Promise.all with loading and error states for each

Industry Examples

Axios

HTTP client returning Promises with interceptors for request/response transformation and error handling

Prisma

Database client returning Promises for all query operations with fully typed results

Zod

Schema validation library using Promises for async validation with .parseAsync() and .safeParseAsync()

Resources

MDN - Promise

docs

JavaScript.info - Promises

article

Related Questions

How do async/await work and how do they relate to Promises?

mid
async

Explain the JavaScript Event Loop and how it handles asynchronous operations.

mid
runtime
Previous
What is a closure in JavaScript and why are they useful?
Next
How do async/await work and how do they relate to Promises?
PrevNext