Course contentsShow
← JavaScript
Lesson 1268 of 2,72329. PromisesFree lesson

Rejecting a Promise

Call reject(reason) inside the executor to transition the promise from pending to rejected with an error.

Rejecting a Promise

You'll learn how to signal that a promise has failed by calling the reject function inside the executor.

The Core Idea

When you create a promise, you provide an executor function that receives two parameters: resolve and reject. While resolve signals success, reject signals failure. Calling reject(reason) transitions the promise from the "pending" state to the "rejected" state, and the value you pass becomes the rejection reason (typically an error).

Think of it like ordering food: if the restaurant successfully prepares your meal, they "resolve" your order. But if they run out of ingredients, they "reject" your order with a reason why it failed.

How It Works

const failedPromise = new Promise((resolve, reject) => {
  const userAge = 15;
  
  if (userAge >= 18) {
    resolve("Access granted");
  } else {
    reject("User must be 18 or older"); // Promise now rejected
  }
});

The rejection reason can be any value, but it's conventional to pass an Error object:

const betterPromise = new Promise((resolve, reject) => {
  const fileExists = false;
  
  if (fileExists) {
    resolve("File content here");
  } else {
    reject(new Error("File not found")); // Best practice
  }
});

Once reject() is called, the promise is settled as rejected, and that value becomes available to anyone using the promise (you'll learn how to handle this in upcoming lessons).

Key Takeaway: Call reject(reason) inside the executor function to mark a promise as failed; this transitions it from pending to rejected and captures the reason for failure.