javascript / expert
Snippet
Explicit Resource Management with 'using'
Explicit Resource Management (ERM) introduces the 'using' keyword to manage resources like file handles or database connections. It ensures that resources are disposed of immediately when leaving a scope, reducing memory leaks and avoiding manual cleanup in try/finally blocks.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
class DatabaseConnection {#client;constructor(uri) { this.#client = connect(uri); }[Symbol.dispose]() {this.#client.close();console.log('Connection closed automatically');}}{using db = new DatabaseConnection('mongodb://localhost:27017');// Use db here...} // Scope ends, [Symbol.dispose] is called automatically
nodejs
Breakdown
1
[Symbol.dispose]() { ... }
Defines the synchronous disposal logic for the object.
2
using db = new DatabaseConnection(...)
Binds the resource to the current block scope for automatic cleanup.