hyperledger / fabric-gateway

Go, Node and Java client API for Hyperledger Fabric v2.4+
https://hyperledger.github.io/fabric-gateway/
Apache License 2.0
150 stars 87 forks source link

Explicit resource management (`using` keyword) for Node API #636

Closed bestbeforetoday closed 11 months ago

bestbeforetoday commented 11 months ago

As an Node application developer I want to use explicit resource management (using keyword) So that I don't need to write clean-up code using try/finally blocks to ensure resources are closed after use

TypeScript 5.2 adds support for the using keyword, defined by the upcoming Explicit Resource Management ECMAScript feature. For closeable resources that are only used within a defined scope, this avoids the need for clean-up code (typically implemented using try/finally blocks to ensure it is called in the event of an error) to close resources. It provides similar capability to Java's try-with-resources, and (to some extent) Go's defer.

This feature proposes that all objects in the Node API with close() methods to perform resource clean-up are augmented to implement the Disposable type, and have a [Symbol.dispose] method that calls the existing close().

For example, the existing application code:

const events = await network.getChaincodeEvents(chaincodeName, { startBlock: BigInt(101) });
try {
    for async (const event of events) {
        // Process event
    }
} finally {
    events.close();
}

Could be simplified to the following, with the close() automatically called when the events variable goes out of scope:

using events = await network.getChaincodeEvents(chaincodeName, { startBlock: BigInt(101) });
for async (const event of events) {
    // Process event
}

Tasks:

The following samples should also be updated once this capability is published: