I am using async/await
in my Node.js project. And in some places I need to return an error from async
function. If I'd use Promises, I could've accomplish it this way:
function promiseFunc() {
return new Promise((res, rej) => {
return rej(new Error('some error'))
})
}
But I'm using async
function, so no res
and rej
methods are there.
So, the question: can I throw
errors in async
functions? Or is it considered a good/bad practice?
An example of what I want to do:
async function asyncFunc() {
throw new Error('some another error')
}
I can also rewrite it this way:
async function anotherAsyncFunc() {
return Promise.reject(new Error('we need more errors!'))
}
but the first one looks more clear to me, and I'm not sure which one should I use.
catch (in combination with async functions) and the . catch() approaches to handle errors for asynchronous code. When returning a promise within a try block, make sure to await it if you want the try... catch block to catch the error.
If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.
I would do:
async function asyncFunc() {
try {
await somePromise();
} catch (error) {
throw error;
}
}
But I think it comes to personal preference I guess? You could always return Promise.reject(new Error(error));
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With