Skip to content

Support for the new using keyword and it's corresponding Disposable interface #492

@peter-leonov-ch

Description

@peter-leonov-ch

Support the new using keyword by providing meaningful finalizers to the disposable resources.

Use case

Cancel queries and close client connections when a given resource goes out of scope.

Describe the solution you'd like

async function main() {
  await using client = await client.query();

  // some code that can throw
  // but thanks to `using` the client will still get closed

  // client is also automatically closed here by calling [Symbol.disaposeAsync]
}

Describe the alternatives you've considered

Without the new using keyword it is required to wrap the code that might leak expensive resources like sockets and big buffers in try / finally

async function main() {
  let client
  try {
    client = await createClient();
  } finally {
    if (client) {
      await client.close()
    }
  }
}

Same should be valid for canceling queries and closing streams.

Additional context

This new JS feature is similar to Go's defer client.close(), Rust's Drop trait and classic C++ destructors in RAII idiom. Unlike FinalizationRegistry which does not give strict guarantees, the using keyword has clear semantics on when and how the resource is disposed of.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions