Reputation: 9193
I have the following code
try {
const result = await doSomething();
}
catch {
console.log('Error loaidng rejected data');
}
// rest of code
My problem is that I'm not doing anything in the catch segment. I'm only including it so that the code continues in case there is an error. If I remove the catch then the whole thing blows up. Is there anyway I can achieve the same without a catch? and without using promises?
Upvotes: 3
Views: 3159
Reputation: 36117
Yes, most of the time try/catch block is huge, to make it concise you can leverage await-to-js
libs. So we can use like below.
const [err, result] = await to(doSomething());
Note that it never blows up because we attached catch handler for this promise.
I just copy the source from https://github.com/scopsy/await-to-js
.
export function to<T, U = Error> (
promise: Promise<T>,
errorExt?: object
): Promise<[U | null, T | undefined]> {
return promise
.then<[null, T]>((data: T) => [null, data])
.catch<[U, undefined]>((err: U) => {
if (errorExt) {
Object.assign(err, errorExt);
}
return [err, undefined];
});
}
export default to;
Upvotes: 0
Reputation: 16127
It is a Promise, then you can ignore the catch
function.
const result = await doSomething().catch(() => null);
Do nothing in error case, your code will continue execute next line, but result
is undefined in this case (error case).
Upvotes: 9
Reputation: 21628
Can I do it without a promise?
No, await is just syntactic sugar to wrap a promise. If your async function does not return a promise then it doesn't make sense to be using await.
You could catch the error inside doSomething and resolve the promise with null or undefined to keep things going.
Upvotes: 2