【问题标题】:how to solve UnhaldedPromiseRejectionWarning when rejecting a promise拒绝承诺时如何解决 UnhandledPromiseRejectionWarning
【发布时间】:2021-11-02 21:34:40
【问题描述】:

我是 JavaScript 新手,我正在学习 Promise。我创建了一个类似于我给出的示例的简单脚本,用于检查是否可以预订一张桌子,并在指定时间解决/拒绝承诺。

如果指定的时间是空闲的,promise 就解决了,没有问题,但是如果它被拒绝,我得到错误

(node:8300) UnhandledPromiseRejectionWarning: Sorry, we won't have a table in  4 hours
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8300) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8300) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

从 google 看来,我应该有一个 try and catch 块来接受和拒绝,但我不确定如何使用 if-else 语句来做到这一点。

如果有人可以帮助解释我收到错误的原因和/或编写此脚本的更好方法,我们将不胜感激。

> let bookedTimes = [1,2,4]
> 
> bookTable = (time) => {
>     console.log(`I would like to book a table in ${time} hours`)
>     return new Promise(function(resolve,reject) {
>         console.log('Checking available tables...')
>         if(bookedTimes.includes(time)){
>             const error = `Sorry, we won't have a table in  ${time} hours`
>             setTimeout(() => {
>               reject(error)
>               console.log(error)
>             }, 2000)
>           } 
>           else {
>             const success = `Success! Your reservation will be ready in ${time} hours`
>             setTimeout(() => {
>               resolve(success)
>               console.log(success)
>             }, 2000)
>             
>           }
>     }) }
> 
> 
> bookTable(4)

【问题讨论】:

  • bookTable(4) ---> bookTable(4).catch(err => console.log(err))

标签: javascript promise unhandled-promise-rejection


【解决方案1】:

一旦您调用bookTable,就会返回一个承诺,该承诺将解决或拒绝。

就像任何其他承诺一样,您需要为这两种情况做好准备。

bookTable(4).then(resolveValue=>...).catch(rejectValue=>...) // specify in then and catch what you want to do with those values.

当你没有任何计划以防 promise 被拒绝时,你的错误就出现了,上面一行是 catch 方法。

处理此问题的另一种方法是按照您的指示使用 try and catch

【讨论】:

  • 啊,谢谢,我没有意识到我的方法没有处理拒绝。
猜你喜欢
  • 2013-06-22
  • 2023-03-26
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2018-11-17
相关资源
最近更新 更多