AsyncDisposableStack.prototype.move()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

move() 方法是 AsyncDisposableStack 例項的方法,它會建立一個新的 AsyncDisposableStack 例項,該例項包含與當前堆疊相同的處置器,然後將當前堆疊標記為已處置,而不會呼叫任何處置器。

語法

js
move()

引數

無。

返回值

一個新的 AsyncDisposableStack 例項。

異常

ReferenceError

如果堆疊已被處置,則丟擲異常。

示例

宣告對堆疊的所有權

js
async function consumeStack(stack) {
  await using newStack = stack.move(); // newStack now owns the disposers
  console.log(stack.disposed); // true
  console.log(newStack.disposed); // false
  // newStack is disposed here immediately before the function exits
}

const stack = new AsyncDisposableStack();
console.log(stack.disposed); // false
await consumeStack(stack);
console.log(stack.disposed); // true

允許在兩個程式碼路徑中處置資源

move() 的主要用例是當你有一個或多個資源,這些資源可以立即在此處處置,也可以保留以供將來使用。在這種情況下,你可以將這些資源放入 AsyncDisposableStack 中,然後在需要保留這些資源以供將來使用時呼叫 move()

js
class PluginHost {
  #disposed = false;
  #disposables;
  #channel;
  #socket;

  static async init() {
    // Create a AsyncDisposableStack that is disposed when init exits.
    // If construction succeeds, we move everything out of `stack` and into
    // `#disposables` to be disposed later.
    await using stack = new AsyncDisposableStack();

    const channel = stack.use(await getChannel());

    const socket = stack.use(await getSocket());

    // If we made it here, then there were no errors during construction and
    // we can safely move the disposables out of `stack`.
    return new PluginHost(channel, socket, stack.move());

    // If construction failed, then `stack` would be disposed before reaching
    // the line above, which would dispose `channel` and `socket` in turn.
  }

  constructor(channel, socket, disposables) {
    this.#channel = channel;
    this.#socket = socket;
    this.#disposables = disposables;
  }

  [Symbol.asyncDispose]() {
    if (this.#disposed) {
      return;
    }
    this.#disposed = true;
    // Put `this.#disposables` into a `using` variable, so it is automatically
    // disposed when the function exits.
    await using disposables = this.#disposables;

    // NOTE: we can free `#socket` and `#channel` here since they will be
    // disposed by the call to `disposables[Symbol.asyncDispose]()`, below.
    // This isn't strictly a requirement for every disposable, but is
    // good housekeeping since these objects will no longer be useable.
    this.#socket = undefined;
    this.#channel = undefined;
    this.#disposables = undefined;
  }
}

規範

規範
ECMAScript 非同步顯式資源管理
# sec-asyncdisposablestack.prototype.move

瀏覽器相容性

另見