简体   繁体   English

在express.js中,当我使用Promise时,是否需要在执行程序中包含reject()?

[英]In express.js, when I use promises, do I need to include reject() in the executor?

In the situation that we do not deal with reject, must we include reject in the promise executor? 在我们不处理拒绝的情况下,我们必须在承诺执行者中包括拒绝吗?

for example: 例如:

 new promise ((res)=>{
   res(a);
 })

It's not necessary, no, but it's not a very elegant way to handle errors - if an error is thrown whilst your promise is pending, you'll want to take some other action and reject the promise, letting the user know what's wrong. 这不是必须的,不是,但这不是处理错误的一种绝妙的方式-如果在您的诺言未决期间抛出错误,您将需要采取其他措施并拒绝诺言,让用户知道出了什么问题。

Have a look at MDN Promise Docs , they explain the concept of handling errors in Promises pretty well! 看看MDN Promise Docs ,他们很好地解释了Promises中处理错误的概念!

If you know that a promise will never be rejected, adding a rejection handler is not necessary. 如果您知道一个承诺将永远不会被拒绝,则无需添加拒绝处理程序。 Eg it's obvious this will never be rejected and adding a rejection handler would be plain silly: 例如,很明显,这将永远不会被拒绝,添加拒绝处理程序将很愚蠢:

Promise.resolve("abc")
    .then(result => console.log(result));

In all other cases, not providing a rejection handler is pretty much the same as not wrapping an error-throwing piece of code in try - catch . 在所有其他情况下,不提供拒绝处理程序与在try - catch不包装抛出错误的代码几乎相同。 It might be intentional, of course, but bear in mind that node.js will treat unhandled promise rejections as if they were uncaught errors: by terminating the node.js process. 当然,这可能是故意的,但请记住,node.js将未处理的承诺拒绝视为未捕获的错误:通过终止node.js进程。 That's what it says on the console when an unhandled promise rejection occurs: 当发生未处理的承诺拒绝时,这就是控制台上的内容:

(node:7741) DeprecationWarning: Unhandled promise rejections are deprecated. (节点:7741)已弃用警告:已弃用未处理的承诺拒绝。 In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。

So, summing up: 因此,总结一下:

  • skip rejection handlers when you know for a fact a rejection is impossible, 当您知道拒绝是不可能的情况时,请跳过拒绝处理程序,
  • skip rejection handlers when you require the application be terminated upon rejection (in future versions of Node.js), 当您要求应用程序在拒绝时终止(在将来的Node.js版本中)时,请跳过拒绝处理程序,
  • write rejection handlers in all other cases. 在所有其他情况下,编写拒绝处理程序。

EDIT (the question became clearer after the edits were made, hence my update to the answer): 编辑(进行编辑后,问题变得更加清晰,因此我对答案进行了更新):

As for including the reject() call in the promise executor, no, you do not need to add it. 至于在promise执行器中包括reject()调用,不,您不需要添加它。 Again though, you have to make sure that the internal logic guarantees that resolve() will always be called. 同样,您必须确保内部逻辑保证始终调用resolve()

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

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