. Advertisement .
..3..
. Advertisement .
..4..
For those who are technology people, they are all too familiar with the concept of programming node.js. However, the manipulation process in the program cannot avoid the problems, especially the youth who are new to running code. Today, we will give an example of a node.js problem that you can face and how to solve it as well, it is the “Unhandled Promise Rejection” error by the asyncActions. Follow this article to find the suitable method for you!
Why does the error “Unhandled Promise Rejection” occur?
You may encounter the error:
[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 “…”.] { code: ERR_UNHANDLED_REJECTION’ }
There are many reasons of this error. They are:
- To use await calls, you place your code inside an async function.
- Your
await
ed functions does not work (it means that a promise is rejected). - An
await
call is put inside a block of try/catch or you utilize .catch(). - To end the script, you throw an error in the catch block.
How to solve the error “Unhandled Promise Rejection”
Option 1: Utilize .catch() as the following suggestion
To solve the error “unhandled promise rejection”, you can utilize .catch()
as the following suggestion:
await returnsPromise().catch(e => { console.log(e) })
Or you can try to use a try/catch block:
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
}
Option 2: Include .catch() in the call to the wrapper function
Another way for your problem is including .catch()
in the call to the wrapper function, thus you don’t have to include the try/catch block inside the wrapper. Look at below:
(async function () {
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
throw error
}
})().catch( e => { console.error(e) })
Moreover, you can use process.exit(1)
rather than throw
to finish the script, it’s very efficient.
(async function () {
try {
await returnsPromise()
} catch (error) {
console.error(error)
process.exit(1)
}
console.log('This will not be printed.');
})()
Two methods above are very simple, but they are very helpful for you. After you apply them for your error, it will be disappear and your program will run well without any errors. Therefore, let’s use them to get your desired results.
Conclusion
In conclusion, we have provided you with more information about common errors in the Node.js and how to fix the “Unhandled Promise Rejection” warning. Hope it helps you to handle your problem and have a good day ahead!
Read more
Leave a comment