Is this code valid?
Yes. (In terms of the try
/catch
aspect, see "side note" below.)
I was wondering if I should add try...catch
to func2
, but I came to conclusion it's already being handled in the try...catch
of func1
.
Yes, it is. Just like with non-async
functions, you only need the try
/catch
in func2
if you want to handle the error there (entirely, or partially and then (re)throwing). If you don't, allow it to propagate to the caller. Just ensure it's handled somewhere.
Side note: I'm assuming your func2
has a return
in the case where response1
is a falsy value. If not, func2
's promise's resolution value will be undefined
in that case.
Side note 2: I'm guessing you've added the func1 =
part there just to give yourself a name to refer to in the question and it's not in your real code. But in case it is: Unless you've declared it somewhere you haven't shown, in your example func1
is an implicit global. Recommend avoiding those. :-) More in my blog post: The Horror of Implicit Globals
Side note 3 (he does go on a bit, doesn't he?): If you're not using func1
anywhere else (just using it as a wrapper for convenient await
use within it), if you want to, you can avoid a level of indentation by using the fact that async
functions return promises:
(async () => {
const response = await func2();
console.log('Success!');
})().catch(e => {
console.log('Failed!');
});
The up side is that it's a bit more concise. The downside is that it mixes metaphors. :-) That and the try
/catch
do exactly the same thing, it's purely a matter of how you prefer to write it, which is entirely up to you.