← Back to Chapters

JavaScript Promises

⚙️ JavaScript Promises

? Quick Overview

A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises help you write cleaner, more readable asynchronous code and avoid deeply nested callbacks.

? Key Concepts

  • Asynchronous operations: Promises wrap tasks that complete later (like API calls or timers).
  • Three states: pending, fulfilled, and rejected.
  • Handlers: Use .then() for success and .catch() for errors.
  • Chaining: You can return values from .then() and build step-by-step workflows.
  • Promise utilities: Methods like Promise.all() let you work with multiple Promises together.

? Syntax and Theory

You create a Promise using the new Promise() constructor. It takes an executor function with two parameters: resolve (for success) and reject (for failure).

  • resolve(value) → moves the Promise from pending to fulfilled.
  • reject(reason) → moves the Promise from pending to rejected.
  • .then(onFulfilled) runs when the Promise is fulfilled.
  • .catch(onRejected) runs when the Promise is rejected.
  • Each .then() returns a new Promise, which enables chaining.

? Code Examples

?️ Creating a Promise

This example shows how to create a Promise that may resolve or reject based on a condition.

? View Code Example
let promise = new Promise(function(resolve, reject) {
// Do something...
let success = true;

if (success) {
resolve("Operation was successful!");
} else {
reject("There was an error.");
}
});

? Consuming a Promise

Use .then() to handle success and .catch() to handle errors.

? View Code Example
promise.then(function(result) {
console.log(result);
}).catch(function(error) {
console.error(error);
});

✅ Simple Success Example

A Promise that always resolves successfully.

? View Code Example
let promise = new Promise(function(resolve, reject) {
resolve("Success!");
});

promise.then(function(message) {
console.log("Message:", message);
});

❌ Rejected Promise Example

A Promise that is rejected and handled with .catch().

? View Code Example
let promise = new Promise(function(resolve, reject) {
reject("Oops! Something went wrong.");
});

promise
.then(result => console.log(result))
.catch(error => console.error("Error:", error));

⏱️ Promise with setTimeout

This example simulates a delayed operation using setTimeout().

? View Code Example
let loading = new Promise(function(resolve, reject) {
setTimeout(() => {
resolve("Data loaded!");
}, 2000);
});

loading.then(result => console.log(result));

? Chaining Promises

Each .then() can transform the value and pass it to the next .then().

? View Code Example
new Promise((resolve, reject) => {
setTimeout(() => resolve(5), 1000);
})
.then(result => {
console.log(result); // 5
return result * 2;
})
.then(result => {
console.log(result); // 10
return result * 2;
});

? Using Promise.all()

Promise.all() runs multiple Promises in parallel and waits for all to finish.

? View Code Example
let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = Promise.resolve(3);

Promise.all([p1, p2, p3]).then(values => {
console.log(values); // [1, 2, 3]
});

? Live Output / Explanation

  • Simple Success: Logs Message: Success! to the console.
  • Rejected Promise: Skips .then() and logs Error: Oops! Something went wrong. from .catch().
  • setTimeout Example: After ~2 seconds, logs Data loaded!.
  • Chaining Example: Logs 5 first, then 10, showing how values flow through the chain.
  • Promise.all(): Logs [1, 2, 3] when all Promises are fulfilled. If any one rejects, the whole Promise.all() rejects.

? Tips & Best Practices

  • Use Promises to avoid deeply nested callbacks (callback hell).
  • Always handle errors using .catch() so failures don’t crash silently.
  • Use Promise.all() when you need to run independent tasks in parallel and wait for all of them.
  • Create resolved or rejected Promises quickly with Promise.resolve() and Promise.reject().
  • Remember to return values or Promises inside .then() when you want proper chaining.
  • When using timers like setTimeout(), wrap them in a Promise if you want to chain them cleanly.

? Try It Yourself

  • Create a Promise that simulates downloading a file with a 3-second delay and logs a success or error message.
  • Chain multiple .then() calls to process a numeric result step-by-step (e.g., double, then add 10).
  • Use Promise.all() with a few timeout-based Promises (1s, 2s, 3s) and log the array of results.
  • Convert an existing callback-based function into a Promise-based version and use .then()/.catch() to handle it.