🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

Promises

AI & DATA SCIENCE // promises

A Promise represents an eventual value (or failure). It can be pending, fulfilled, or rejected. Use .then() and .catch() to handle results.

Syntax

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('done'), 1000);
});
p.then(val => console.log(val)).catch(err => console.error(err));

Deep Dive Course

**Promises** solved callback hell. A Promise is an object representing an **asynchronous operation** that will eventually succeed (resolved) or fail (rejected). Chain `.then()` for success and `.catch()` for errors. Promises are always asynchronous — `.then()` callbacks never run synchronously.

1Understanding Promises

Promises solved callback hell. A Promise is an object representing an asynchronous operation that will eventually succeed (resolved) or fail (rejected). Chain .then() for success and .catch() for errors. Promises are always asynchronous — .then() callbacks never run synchronously.

💡

Promise.all() runs promises in parallel and fails fast. Promise.allSettled() runs all and gives all results regardless of failures.

editor.html
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: 'Alice' });
      else reject(new Error('Invalid ID'));
    }, 500);
  });
}

fetchUser(1)
  .then(user => console.log(user.name))
  .catch(e  => console.error(e.message));
localhost:3000

2Practical Example

Here is a real-world application of Promises showing how it is used in production JavaScript code.

editor.html
// Promise combinators
const p1 = fetch('/api/users');
const p2 = fetch('/api/posts');
const p3 = fetch('/api/comments');

// Run all in parallel
Promise.all([p1, p2, p3])
  .then(([users, posts, comments]) => { /* all 3 done */ })
  .catch(e => console.error('At least one failed:', e.message));
localhost:3000

3Best Practices

Follow these guidelines when working with Promises:

1. Always add .catch() or a rejection handler

2. Return Promises from async functions

3. Use Promise.allSettled() when you need all results even if some fail

⚠️

Tip: Promise.all() runs promises in parallel and fails fast. Promise.allSettled() runs all and gives all results regardless of failures.

editor.html
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: 'Alice' });
      else reject(new Error('Invalid ID'));
    }, 500);
  });
}

fetchUser(1)
  .then(user => console.log(user.name))
  .catch(e  => console.error(e.message));
localhost:3000

Examples

Example 01Basic Usage
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: 'Alice' });
      else reject(new Error('Invalid ID'));
    }, 500);
  });
}

fetchUser(1)
  .then(user => console.log(user.name))
  .catch(e  => console.error(e.message));
Example 02Advanced Example
// Promise combinators
const p1 = fetch('/api/users');
const p2 = fetch('/api/posts');
const p3 = fetch('/api/comments');

// Run all in parallel
Promise.all([p1, p2, p3])
  .then(([users, posts, comments]) => { /* all 3 done */ })
  .catch(e => console.error('At least one failed:', e.message));

Best Practices

  • Always add .catch() or a rejection handler
  • Return Promises from async functions
  • Use Promise.allSettled() when you need all results even if some fail

Interview Question

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

Hint: Fail-fast vs complete-regardless.

Promise.all() rejects as soon as ANY promise rejects (fail-fast). The other pending promises still run but their results are discarded. Promise.allSettled() waits for ALL promises and returns an array of { status: 'fulfilled'|'rejected', value|reason } objects — never rejects. Use allSettled when you need all results even if some fail.

Exercises

MediumPractice using Promises in a real scenario.
View Solution
function fetchUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id > 0) resolve({ id, name: 'Alice' });
      else reject(new Error('Invalid ID'));
    }, 500);
  });
}

fetchUser(1)
  .then(user => console.log(user.name))
  .catch(e  => console.error(e.message));

Frequently Asked Questions

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

Promise.all() rejects as soon as ANY promise rejects (fail-fast). The other pending promises still run but their results are discarded. Promise.allSettled() waits for ALL promises and returns an array of { status: 'fulfilled'|'rejected', value|reason } objects — never rejects. Use allSettled when you need all results even if some fail.

Related Functions

thencatchawaitAsync-ErrorsetTimeout