An Exercise with Debugging and Promises
Dave
Posted on July 28, 2022
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:
getResult returns a Promise with a 50% chance to succeed and a 50% chance to reject.
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)
})
}
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))
}
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'
}
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()
?
Posted on July 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.