I am running automated tests in a Docker container and using a browser in this environment. I have a concern about whether the browser is closing properly in the scenario below. My code includes a try block with an early return statement. My question is: In JavaScript, if I execute an early return in a try block, will the finally block still be triggered? I want to ensure that the browser is closed correctly in my Docker-based test environment.
try {
await importWallet(params.seedPhrase, page, extensionId)
await addNetwork({networkName: 'BTC', page, extensionId})
await connectWallet(context, page)
return await sendToken({page, params})
}
finally {
await context.close()
console.log('🌂 Closing browser')
}
I ran my test, but I am unable to verify it as it runs in a Docker container.
3
Answers
The try statement defines a code block to run (to try).
The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the result.
The throw statement defines a custom error.
So for your question, Finally statement will work for sure when you run error handling.
finally
block is executed right before returning fromtry
. If you return fromfinally
the returned value fromtry
is ignored despite being evaluated.From MDN, when
finally
is executed (one of the options):The same for throwing an error:
If only there was a convenient JavaScript runtime available in some ubiquitous application like your browser…
You can clearly see from the logged output that the async code in the
finally
is evaluated and awaited before resolving the promise with thereturn
value.