4

Here is the simplified version of the problem;

there are some promises, few .then() chains, and a .catch() block for error handling; each promise might resolve or reject hence I use Promise.allSetted to know which promise had been failed based on their order in array and their status; It works fine when all promises resolve but when a promise is rejected, it's status will be shown as "fulfilled" in Promise.allSetteld; If I remove the .catch() block, It will work as expected but we need to keep the .catch() block for logging to the store; So why isn't it just behave as expected? is there any way to make it show "rejected" status with .catch() block?

let a = Promise.resolve("a: Promise.resolved").then(response => response).catch(err=>console.log(err));

let b = Promise.reject("b: Promise.rejected").then(response => response); // no error handling

let e = Promise.reject("e: Promise.rejected").then(response => response).catch(err=>console.log(err));

Promise.allSettled([a,b,e]).then( values => console.log(values) );
Mechanic
  • 5,015
  • 4
  • 15
  • 38

2 Answers2

7

You can throw the error from the catch block, so that the error is not handled in the catch:

let a = Promise.resolve("a: Promise.resolved").then(response => response).catch(err => console.log(err));

let b = Promise.reject("b: Promise.rejected").then(response => response); // no error handling

let e = Promise.reject("e: Promise.rejected").then(response => response).catch(err => {
  console.log(err);
  throw err;
  //or Reject the Promise
  //return Promise.reject(err)
});

Promise.allSettled([a, b, e]).then(values => console.log(values));

This is also discussed in the Mozilla docs:

p.catch(onRejected);

onRejected

A Function called when the Promise is rejected.

This function has one argument: reason The rejection reason. The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

Yeah now I understand, we .catch() it! so by using .catch() (or catch in try{}catch(e){}) we are telling the program: "Don't panic, everything is under control", " I'll handle that". and that make sense now. if we handle it without throwing errors it sounds like everything is fine; so yeah, why not; it should be fulfilled

Mechanic
  • 5,015
  • 4
  • 15
  • 38