'return await' in a try/catch
Daniel Bellmas
Posted on December 9, 2023
This might sound weird to you, the first thing that comes to mind is: 'Eslint will tell me to remove the await, there is no need for an await after a return'
But the case is a different when we wrap our promise in a try/catch
.
async function foo() {
try {
return await waitAndMaybeReject();
} catch (e) {
return 'caught';
}
}
This also applies when we don't need to return resolved value of the promise, we always need to await it if the returned promise is inside a try/catch
and we want to catch the error.
By returning a promise, we’re deferring its result, so our catch block never runs.
This also happens, when not awaiting a promise (regardless if we return or not).
Only outside of try/catch blocks,
return await
is redundant. There’s even an Eslint rule, but this rule allows a return if it's intry/catch
.
Bonus🔥
If you want to print something after a return statement, instead of temporaraly creating a variable, printing and then returning, like this:
async function foo() {
const res = await fetch();
console.log('after fetch')
return res;
}
We can wrap the return with a try and finallly (unless you need to print the resolved value of the promise of course), like so:
async function foo() {
try {
return await fetch();
} finally {
console.log('after fetch')
}
}
Posted on December 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.