JavaScript .reject()

Anonymous contributor's avatar
Anonymous contributor
Published Jul 27, 2021Updated Aug 17, 2023
Contribute to Docs

Returns a rejected Promise object with a given reason.

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

Promise.reject(reason);

The reason can be most data types, including:

  • numbers
  • strings
  • objects ( ones of type Error recommended for improved error-catching)

Example

A new Promise, myPromise, is rejected with an Error message by default. Lastly, the error message, err.message, is logged to the console through the catch-block.

const myPromise = Promise.reject(new Error('Promise rejected'));
myPromise.catch((err) => {
console.log(err.message); // Output: Promise rejected
});

Codebyte Example

The example below demonstrates rejecting a promise with a string value as the given reason.

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours