Adding a defer keyword like what we do in Golang should be super useful when it comes to multiple returns in different branches in a function which requires cleanup before each return.
I'm curious about why no one has came up with this idea or just I didn't find one...
I think this should be linked to the destructor idea.
And it's still something different: while in Go, we can defer any function, which could be cleanup or some other functionalities. In this particular proposal, it focuses only on one object, which acts more like destructors in other languages like C++.
JS already has try/finally (in contrast to Go), so it doesn't need the defer functionality. Sure, I like Go's approach, but there's no need to have two mechanism that do more or less the same thing. You can even emulate Go's behaviour quite easily:
const defers = [];
try {
if (β¦) {
const res = getResource();
defers.push(() => res.dispose();
β¦
}
if (β¦) {
if (β¦) {
return
}
const file = open();
defers.push(() => file.close());
β¦
}
} finally {
for (cleanup of defers.reverse()) {
cleanup();
}
}
Sure enough we can achieve the same functionality using try/finally, but just like we already have callbacks and then we have Promise then async await, simplifying the procedure of doing the same thing and plus we get the benefit of writing more organized code should be a good thing to happen.