大网数据广告活动
Web 标准与前端开发

DisposableStack.prototype.adopt()

· 52CE 我爱测

The **`adopt()`** method of DisposableStack instances registers a value that doesn't implement the disposable protocol to the stack by providing a custom disposer function.

The adopt() method of DisposableStack instances registers a value that doesn't implement the disposable protocol to the stack by providing a custom disposer function.

Syntax

adopt(value, onDispose)

Parameters

  • value
    • : Any value to be registered to the stack.
  • onDispose
    • : A function that will be called when the stack is disposed. The function receives value as its only argument.

Return value

The same value that was passed in.

Exceptions

  • TypeError
    • : Thrown if onDispose is not a function.
  • ReferenceError
    • : Thrown if the stack is already disposed.

Description

The primary purpose of adopt() is to register a value that doesn't implement the disposable protocol to the stack. If the value is already disposable, you can use DisposableStack/use instead, which automatically uses the value's [Symbol.dispose]() method as the disposer.

adopt(value, onDispose) is almost the same as defer(() => onDispose(value)), but it allows you to declare the resource and register it on the same line. This way, there's minimal chance of an error happening between the resource creation and registration, which will cause the resource to leak.

using disposer = new DisposableStack();
const reader = disposer.adopt(stream.getReader(), (reader) =>
  reader.releaseLock(),
);
using disposer = new DisposableStack();
const reader = stream.getReader();
// If someone adds code in between these lines and an error occurs,
// the stream will be locked forever.
disposer.defer(() => reader.close());

In the same spirit of "make your resource registered as soon as it's declared", you should always wrap your resource acquisition expression in adopt(), instead of extracting it to a separate statement.

using disposer = new DisposableStack();
const reader = stream.getReader();
disposer.adopt(reader, (reader) => reader.close());

Examples

Using adopt()

This code consumes a ReadableStream via a ReadableStreamDefaultReader. The reader does not implement the disposable protocol, so we use adopt() to register it to the stack.

{
  using disposer = new DisposableStack();
  const reader = disposer.adopt(stream.getReader(), (reader) =>
    reader.releaseLock(),
  );
  const { value, done } = reader.read();
  if (!done) {
    // Process the value
  }
  // The reader.releaseLock() method is called here before exiting
}

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。