⏲ Go Defer in JS ⏲
In Go, there is a very cool defer operator that allows you to postpone the execution of any operation until the end of a function (regardless of whether it's a return or an error thrown at the current or lower levels)
For example, closing access to a database when exiting a function where it was opened would look something like this:
db := pg.connect() defer db.destroy()
// A bunch of logic and if there's a return or an error thrown, db.destroy() will be executed // ...
I've always regretted that JS didn't have such an operator, but I've finally found an alternative, and it's try ... finally ...
It seems obvious, but for some reason, I never thought of it, so the above example would be:
const db = pg.connect()
try {
// A bunch of logic and if there's a return or an error thrown, db.destroy() will be executed
// ...
} finally {
db.destroy()
}
Not as elegant, but it provides the ability to execute an operation 100% when exiting a function
I've made a gist with tests