typescript / expert
Snippet
Deterministische Ressourcenfreigabe mit `await using`
`await using` (TC39 Explicit Resource Management, seit TypeScript 5.2) bindet ein AsyncDisposable an den Block-Scope und ruft beim Verlassen — auch im Fehlerfall — dessen `Symbol.asyncDispose`-Methode auf. Das ersetzt den try/finally-Boilerplate für Verbindungspools, Dateihandles oder Locks und garantiert geordnete Freigabe mehrerer Ressourcen in LIFO-Reihenfolge. Mit `AsyncDisposable` bekommt man RAII-Semantik, die auch über asynchrone Kontrollflüsse hinweg trägt.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
class DbConnection implements AsyncDisposable {constructor(public readonly id: string) {}async query(sql: string): Promise<unknown[]> { return []; }async [Symbol.asyncDispose](): Promise<void> {console.log(`closing ${this.id}`);}}async function fetchUsers(): Promise<unknown[]> {await using conn = new DbConnection("main");return conn.query("SELECT * FROM users");}
Erklärung
1
class DbConnection implements AsyncDisposable {
Erklärt die Konformität zum AsyncDisposable-Vertrag.
2
async [Symbol.asyncDispose](): Promise<void> {
Aufräum-Hook, den die Runtime beim Scope-Ende awaited.
3
await using conn = new DbConnection("main");
Bindet conn für den restlichen Block; Freigabe läuft auch bei Throw.
4
return conn.query("SELECT * FROM users");
Das ausstehende Promise wird vor der Freigabe abgewartet — dank await using.