crazyfrog
crazyfrog

Reputation: 247

Problem with catching the reject in promises

I have an exercise to make a promise which ends with failure which returns the string "Failure". I have to use then to manipulate the error.

The problem is that my output is just the reason of the reject and it doesn't even go to then and it doesn't console.log my string

My code:

const myPromise = new Promise((resolve, reject) => {
    reject("failure").then(console.log("ended with failure"))
})
console.log(myPromise)

What have I done wrong?

Upvotes: 0

Views: 160

Answers (2)

Waleed Ahmad
Waleed Ahmad

Reputation: 494

Promises are handled using .then() & .catch() method.

These methods are called exactly when the promise is either:

  • resolved,
  • rejected

Remember this:

  • Whenever a promise is resolved without any ERROR OR REJECTION, it will go in the .then method.
  • If there are error, exception or rejection, it will go in the .catch method.

lets look at an example of a promise being resolved successfully.

const myPromise = new Promise((resolve, reject) => {
  resolve("this will resolve this promise");
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// this will resolve this promise
// Promise resolved came in .then block

example # 2: Example of rejection:

// a rejected promise goes to .catch block
const myPromise = new Promise((resolve, reject) => {
  reject("this will reject this promise");
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// this will reject this promise
// promise with error came in .catch block 

example # 3: Example of Error:

// incase of error goes to .catch block
const myPromise = new Promise((resolve, reject) => {
  throw "sample exception";
});

myPromise
  .then((elem) => console.log("Promise resolved came in .then block"))
  .catch((error) => console.log("promise with error came in .catch block ", error));

// prints 
// promise with error came in .catch block 

Hopefully, by now you understand the purpose of these blocks now. If any questions please let me know.

Upvotes: 2

Ayzrian
Ayzrian

Reputation: 2465

The right way to do that will be.

const myPromise = new Promise((resolve, reject) => {
      reject("failure");
})
myPromise.catch(() => console.log("Caught an error!"));

resolve and reject are just functions that change the state of a promise, but not promises themself.

UPD: Please have look at this doc https://javascript.info/promise-basics it may help to learn promises.

Upvotes: 2

Related Questions