What JavaScript using disposes after returns and exceptions: nine checks
using registers an object with a disposal method in a scope and calls cleanup when that scope ends. When several resources were registered, they were disposed in reverse acquisition order. An early return followed the same rule. Nine conditions in Node.js covered disposal order, retained exceptions, and asynchronous waiting. Before using it, check which object supplies disposal and which scope…
Nine checks in Node.js detail how JavaScript disposes of objects after returns and exceptions. Using registers objects with disposal methods in a scope, disposing them when the scope ends. Multiple resources follow reverse acquisition order for disposal. Nine conditions in Node.js cover disposal order, retained exceptions, and asynchronous waiting before use. Check the object supplying disposal and the scope exit that triggers cleanup before using.
Disposal completes before the caller receives a return value. The provided code, executed as an .mjs file in Node.js 24.15.0, demonstrates this. Using creates objects with a Symbol.dispose method, which logs calls to the disposal process. Disposal of both objects finished before the return value was received.
The ECMAScript declaration and scope specification describe disposing resources registered through using when scope processing finishes. This includes failures as well as normal completion. Both disposals occurred in the order of acquisition, with A disposing before B.
Exception handling in the body led to A disposing before entering the catch. B was disposed before throwing an error, while the body threw an error during disposal. Both exceptions were suppressed, retaining their messages. Cleanup continued even after a disposal failed, keeping earlier errors in a related chain.
An experiment with an asynchronously disposable value showed that it required await using for proper disposal. An object with only Symbol.asyncDispose in a using declaration caused a TypeError. Asynchronous disposal needed separate handling, as a real Node.js temporary directory demonstrated. The directory and its contents were removed when the exception left the scope. Node.js 24.15.0 introduced mkdtempDisposableSync, which returns an object with a path and disposal method for removal.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.