How JavaScript's using statement disposes resources after returns and exceptions
The using declaration registers an object with a disposal method and calls it when the enclosing scope ends. In a Node.js 24.15.0 test, multiple resources were disposed in reverse order of acquisition, including after an early return. Failure cases showed that if a disposal throws, remaining disposals still run and errors are chained through SuppressedError, so logging only the outer message can hide the original failure. Acquisition failures do not trigger disposal of the resource being acquired, so the acquisition function must clean up partial work itself. Asynchronous disposal with await using behaved in order, and passing a value with only asyncDispose to using without await raised a TypeError.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in