Can I reset the error in an asynchronous function?
I am using async/await
Node.js in my project. And in some places I need to return an error from the function async
. If I was using Promises I could execute it like this:
function promiseFunc() {
return new Promise((res, rej) => {
return rej(new Error('some error'))
})
}
But I am using a function async
, so there are no methods res
and rej
. So the question is: can I have throw
errors in the functions async
? Or is this considered 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 like this:
async function anotherAsyncFunc() {
return Promise.reject(new Error('we need more errors!'))
}
but the first one seems more clear to me and I'm not sure which one I should use.
I would do:
async function asyncFunc() {
try {
await somePromise();
} catch (error) {
throw new Error(error);
}
}
But I think it is about personal preference, I guess? You can always return Promise.reject(new Error(error));
.