简体   繁体   English

为什么在 Promise.reject() 上使用 catch 会将其更改为已履行的承诺?

[英]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:今天我只是在探索 JavaScript 中的 Promises,我遇到了这个:

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..catch的调用将返回一个挂起的承诺。

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.如果承诺实现,那么catch承诺将效仿并解决相同的结果,而不会执行作为参数传递的回调。

  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.如果调用它的承诺被拒绝(如您的示例中所示),则执行回调(作为参数传递给catch )。 This execution determines how the catch -returned promise (that was pending) is resolved.此执行确定如何解决catch返回的承诺(挂起)。 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.每个Promise.thenPromise.catch返回一个已履行的承诺,其值是从function处理程序返回给thencatch子句的。

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".第一个Promise.reject("Failed")返回一个被拒绝的 promise,其值为“Failed”。 The catch clause has an arrow functions. catch子句有一个箭头函数。 And what is this arrow function returning you may ask?你可能会问这个返回的箭头函数是什么? The value returned by console.log which is undefined. console.log返回的值未定义。

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?";
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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