简体   繁体   中英

Why does using catch on Promise.reject() changes it to a fulfilled promise?

Today I was just exploring Promises in JavaScript and I came across this:

Promise.reject("Failed");

Gives

Promise { <state>: "rejected", <reason>: "Failed" }
Uncaught (in promise) Failed

Whereas,

Promise.reject("Failed").catch((reason) => console.log(reason));

Gives

Failed
Promise { <state>: "fulfilled", <value>: undefined }

I get the part that in the latter, the rejection is caught and hence just a normal console message but why is the promise itself changed to fulfilled when it was rejected.

A call to .catch will return a pending promise.

Whether that pending promise will fulfill depends on:

  1. The promise on which it is called. It that promise fulfils, then the catch promise will just follow suit and resolve to the same outcome without ever executing the callback that was passed as argument.

  2. If the promise on which it is called is rejected (like in your example), then the callback (passed to catch as argument) is executed. This execution determines how the catch -returned promise (that was pending) is resolved. For instance, if the callback throws an error, that promise will actually get in a rejected state.

Demo:

 let p = Promise.reject(); let q = p.catch(() => { console.log("p rejected"); // Return a promise that will reject 1 second later return new Promise((resolve, reject) => setTimeout(reject, 1000)); }); let r = q.catch(() => { console.log("q rejected!"); });

Every Promise.then and Promise.catch returns a fulfilled promise with the value returned from the function handler given to then or catch clause.

Let's take a look at your code.

Promise.reject("Failed").catch((reason) => console.log(reason));

The first Promise.reject("Failed") returns a rejected promise with the value "Failed". The catch clause has an arrow functions. And what is this arrow function returning you may ask? The value returned by console.log which is undefined.

How do you test it you may ask? Simple, paste this in your console.

Promise.reject("Failed").catch((reason) => {
 console.log(reason);
 return "Whoa, what is this?";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM