#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read
Question 5 of 50medium

What are Promises in JavaScript?

Understanding Promises for asynchronous operations.

What You'll Learn

  • What Promises are
  • Promise states
  • How to use Promises

What is a Promise?

A Promise is an object representing the eventual completion or failure of an asynchronous operation.

Promise States

StateDescription
PendingInitial state, not fulfilled or rejected
FulfilledOperation completed successfully
RejectedOperation failed

Creating a Promise

code.jsJavaScript
const promise = new Promise((resolve, reject) => {
  const success = true;

  if (success) {
    resolve('Data fetched!');
  } else {
    reject('Error occurred');
  }
});

promise
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log('Done'));

Promise Methods

code.jsJavaScript
// Wait for all promises
Promise.all([p1, p2, p3])
  .then(results => console.log(results));

// First to settle
Promise.race([p1, p2, p3])
  .then(result => console.log(result));

// All settled (success or failure)
Promise.allSettled([p1, p2, p3])
  .then(results => console.log(results));