0

我是 JavaScript 新手,我正在学习 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.

从谷歌看来,我应该有一个 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)
4

1 回答 1

0

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

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

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

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

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

于 2021-09-05T13:13:03.567 回答