Javascript release resources automatically (e.g. RAII)

My general question is, what methods can I use to ensure that resources are cleaned / freed in Javascript? I am currently taking the C approach (without goto) to find each execution path to return or throw away in my functions and provide cleanup.

My specific example is the following: In Node.js, I use mutexes (via file locks) in member functions (I need a mutual exception because I run multiple instances of the Node.js application and when different instances interact with the file system).

For example, in C ++, I would do something like the following:

void MyClass::dangerous(void) { MyLock lock(&this->mutex); ... // at the end of this function, lock will be destructed and release this->mutex. } 

As far as I can tell, JavaScript does not provide any RAII functionality. In C, I would use goto to unwind resource allocation in the event of an error, so I only have one way to return from the function.

What are some methods to achieve a similar effect in Javascript?

+6
source share
1 answer

Use the callback list to call at the end of the area. Call them if necessary.

This approach is used, for example, to de-initialize an additional handler attached to the browser window. Callbacks containing de-initialization code are stored in a list that is processed during a window unload event.

Unfortunately, this approach is in most cases unsuitable for managing the area due to exception security requirements.

+1
source

Source: https://habr.com/ru/post/921516/


All Articles