0
0
JavascriptConceptBeginner · 3 min read

What is Promise.resolve and Promise.reject in JavaScript

Promise.resolve creates a promise that is immediately fulfilled with a given value, while Promise.reject creates a promise that is immediately rejected with a given reason. Both are used to quickly create promises without asynchronous operations.
⚙️

How It Works

Think of a promise as a box that will eventually hold a result. Promise.resolve is like opening a box and finding the result already inside, ready to use. It creates a promise that is already successful with the value you give it.

On the other hand, Promise.reject is like opening a box and finding a note that says something went wrong. It creates a promise that is already failed with the reason you provide.

These methods help you quickly create promises without waiting for anything to happen, which is useful when you want to work with promises but already know the outcome.

💻

Example

This example shows how Promise.resolve and Promise.reject create promises that immediately settle, and how to handle their results.

javascript
Promise.resolve('Success!').then(value => {
  console.log('Resolved with:', value);
});

Promise.reject('Error occurred').catch(reason => {
  console.log('Rejected with:', reason);
});
Output
Resolved with: Success! Rejected with: Error occurred
🎯

When to Use

Use Promise.resolve when you want to wrap a value in a promise to keep your code consistent, especially if some parts return promises and others return plain values.

Use Promise.reject to create a promise that fails immediately, which is helpful for error handling or testing how your code reacts to failures.

For example, if you have a function that sometimes returns a value and sometimes needs to return a rejected promise, these methods make it easy to do so.

Key Points

  • Promise.resolve(value) returns a promise fulfilled with value.
  • Promise.reject(reason) returns a promise rejected with reason.
  • Both create promises that settle immediately without delay.
  • They help unify code that works with promises and plain values.
  • Useful for testing, error handling, and simplifying asynchronous code.

Key Takeaways

Promise.resolve creates a promise that is immediately fulfilled with a given value.
Promise.reject creates a promise that is immediately rejected with a given reason.
Use these methods to quickly create settled promises without asynchronous work.
They help keep code consistent when mixing promises and plain values.
Ideal for error handling, testing, and simplifying promise-based code.