Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readJavaScript

Auto-cleanup with using and Symbol.dispose

Use using and Symbol.dispose to close a handle before releasing its lock, even when your function returns early or throws.

A function takes a lock, opens a handle and may return early. Use using to close the handle and release the lock on either a return or a throw.

Put cleanup at acquisition

In a runtime with explicit resource management, a using declaration registers the object's Symbol.dispose method for cleanup. Declare each resource in the smallest scope that needs it. JavaScript calls its disposer when that scope exits. Run the example with Node 24.

function resource(name) {
  console.log('acquire ' + name)
  return {
    [Symbol.dispose]() {
      console.log('release ' + name)
    },
  }
}

function processBatch(rows) {
  using lock = resource('lock')
  using handle = resource('handle')

  if (rows.length === 0) return 'empty'
  throw new Error('write failed')
}

console.log(processBatch([]))
try {
  processBatch(['row'])
} catch (error) {
  console.log(error.message)
}

Both calls acquire the lock and handle in that order, then release the handle and lock before printing empty or write failed.

diagram

Resource lifetime in processBatch

On either exit, JavaScript releases the handle before it releases the lock that protects it.

The logging objects stand in for your lock and handle APIs. In a real adapter, the symbol method would call the corresponding release or close function. Give each disposer the instance its acquisition function returned. If acquiring the handle throws, the lock still has a cleanup registered.

Keep the lifetime inside the block

Resist returning the handle itself from processBatch. JavaScript would dispose of it on the way out. Return data you read from it or pass it into a function that finishes before the enclosing block exits.

Use await using with Symbol.asyncDispose when the close operation returns a promise you need to wait for. A synchronous using declaration calls its disposer without waiting for a promise it returns.

For a resource that exposes only close(), keep a try/finally or wrap the handle in an object whose Symbol.dispose method calls close().