JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext
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

Code Examples

Creating and using Promises
// 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');
  });

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?