DEV Community

Dave
Dave

Posted on • Edited on

An Exercise with Debugging and Promises

Debugging skills are one of the hardest to gain as someone new to development, so I thought I'd take the time to share some of the exercises that stumped me. Give this one a try!

You have two functions:

  1. getResult returns a Promise with a 50% chance to succeed and a 50% chance to reject.

  2. testGetResult calls getResult and logs the output once.

Here is the implementation that was given to you:

getResult

getResult is an async function that returns a Promise. The Promise will either reject or resolve in 1000 miliseconds, and whether it rejects or resolves depends on a variable generated. The variable will have a value between -0.5 to 0.5; in other words, there is a 50% chance of the variable being positive. If the variable is negative, it rejects. Simple, right?

const getResult = async () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let number = Math.random() - 0.5
      if (number < 0) { reject("failure") }
      resolve("success")
    }, 1000)
  })
}
Enter fullscreen mode Exit fullscreen mode

getTestResult is even more simple.
It initiates a variable called result and simply gets the Promise from getResult(). It will then log whether it succeeded or not.

getTestResult

async function testGetResult() {
  let result = await getResult()

  result.then((res) => console.log(res))
        .catch((err) => console.log(err))
}
Enter fullscreen mode Exit fullscreen mode

The Issue

When running this example, node throws an error:

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: 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(). The promise rejected with the reason "failure".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
Enter fullscreen mode Exit fullscreen mode

What went wrong?

I'll update the post with an answer in a few days :)

Update 08/01

Hint: what is the type being returned from getResult()?

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay