Hi everyone!
I am coming from Python background, and in Python we have context managers.
These are objects encapsulating the try-catch-finally block, and usually are used to cleanup resources, like closing the open file. In Python community, most developers consider context managers a very neat feature of the language and you really can find them often in the code.
So, my question is: why is this feature missing completely in the js world? I could not find a single library. I think I can imagine what it could look like:
import With from 'missing-context-managers'
import open from 'some-file-utils'
With(open(file_path), (file) => {
// file is open now
console.log(file.getContents())
})
// file is closed now
From what I understand, the respective aspects of the language (error handling) is pretty much the same in python and javascript. What is the difference? Why one community finds a feature useful and the other - completely not?
P. S. I am not really asking if you consider context managers useful, just what is the possible difference between js/nodejs and python in this aspect.
Because you have to be able to run some code when a block ends and there are no more references to its resources. That's really hard to do in an async/callback-heavy language like JavaScript. In your example above, the call to
file.getContents()
would probably return immediately, and schedule a callback for later, like Node'sfs.readFile()
. Which means you'd exit theWith
function and close the file handler beforereadFile()
has a chance to run.Alternatively, you could only use synchronous, blocking methods like
fs.readFileSync()
, but then all of your execution is paused while you wait on I/O: a total non-starter....You could probably hack something together generators (or maybe even with promises?), but those have only come to JavaScript recently.