【发布时间】: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