0

I am new to JavaScript and I am learning about promises. I created a simple script similar to the example I was given that checks whether a table can be booked and resolves/rejects the promise if it can or can't at the specified time.

If the time specified is free, the promise is resolved with no issues, but if it is rejected, I get the error

(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.

From google, it seems I should have a try and catch block for the accept and reject, but I am unsure how to do this with the if-else statement.

If anyone can help explain why I am receiving an error and/or what a better way of writing this script, it would be greatly appreciated.

> 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)
Valortome
  • 11
  • 5

1 Answers1

0

Once you call bookTable, a promise is returned, which would either resolve or reject.

Just like any other promise, you need to be ready for both cases.

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

Your error comes when you don't have any plan in case the promise rejects, which in above line is catch method.

An alternative way to handle this is using try and catch as you indicated.

Erfan
  • 1,725
  • 1
  • 4
  • 12