AsyncDisposableStack.prototype.use()
Baseline Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The use() method of AsyncDisposableStack instances registers a value that implements the async disposable protocol to the stack.
See DisposableStack.prototype.use() for general information about the use() method.
Syntax
use(value)
Parameters
-
value - The value to register to the stack. Must either contain a
[Symbol.asyncDispose]()or[Symbol.dispose]()method, or benullorundefined.
Return value
The same value that was passed in.
Exceptions
-
TypeError - Thrown if
valueis notnullorundefined, and does not contain a[Symbol.asyncDispose]()or[Symbol.dispose]()method. -
ReferenceError - Thrown if the stack is already disposed.
Examples
Using use()
This function reads a file (as a Node.js FileHandle) and returns its contents. The file handle is automatically closed when the function completes, given that the FileHandle class implements a [Symbol.asyncDispose]() method that asynchronously closes the file.
async function readFileContents(path) {
await using disposer = new AsyncDisposableStack();
const handle = disposer.use(await fs.open(path));
const data = await handle.read();
return data;
// The disposer is disposed here, which causes handle to be closed too
}
Specifications
Browser compatibility
| Desktop | Mobile | Server | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on iOS | Samsung Internet | WebView Android | WebView on iOS | Bun | Deno | Node.js | |
use |
134 |
134 |
141 |
119 |
preview |
134 |
141 |
88 |
No |
29.0 |
134 |
No |
1.3.0 |
2.2.10 |
24.0.0 |
See also
- JavaScript resource management
AsyncDisposableStackAsyncDisposableStack.prototype.adopt()AsyncDisposableStack.prototype.defer()
© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncDisposableStack/use