iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🦔

Practical Resource Disposal with await using

に公開2件

Practice

The "I wondered when I'd ever use this, and the day finally came" series.

https://zenn.dev/ventus/articles/ts5_2-using-preview

I used it with Deno this time, but it also works in Node.js or browsers if you include a Polyfill.

https://github.com/mizchi/play-ts-using

Wanting to close puppeteer with try-finally

I was writing code like this to handle Puppeteer in Deno.

// original
import puppeteer from "npm:puppeteer@23.6.1";
import chromeFinder from "npm:chrome-finder@1.0.7";
let browser: puppeteer.Browser | null = null;
try {
  browser = await puppeteer.launch({
    headless: false,
    executablePath: chromeFinder(),
  });
  const page = (await browser.pages())[0];
  await page.goto("https://google.com", {
    waitUntil: "networkidle0",
  });
  const title = await page.title();
  console.log(title);
} finally {
  browser?.close();
}

If you forget to call this browser.close(), it is judged that the event listeners have not been released, and the process will not terminate in Deno/Node.
Conversely, even if you force process.exit(0) or Deno.exit(0), this time Chrome will fail to terminate.

So I definitely want to call browser.close(), but since await puppeteer.launch(...) itself is asynchronous and could throw an exception, I am placing a dynamic symbol initialized with let outside the scope.

Ideally, I would want to handle this like linear memory since initialization only happens once, but JavaScript does not have that feature.

await using version

Therefore, I will define a function for await using that schedules processing when exiting the scope, initializing Puppeteer while scheduling browser.close().

import puppeteer from "npm:puppeteer@23.6.1";
import chromeFinder from "npm:chrome-finder@1.0.7";

async function useBrowserContext() {
  const browser = await puppeteer.launch({
    headless: false,
    executablePath: chromeFinder(),
  });
  const page = (await browser.pages())[0];
  return {
    browser,
    page,
    async [Symbol.asyncDispose]() {
      await browser.close();
    },
  };
}

{
  await using ctx = await useBrowserContext();
  await ctx.page.goto("https://google.com", {
    waitUntil: "networkidle0",
  });
  const title = await ctx.page.title();
  console.log(title);
  // Symbol.asyncDispose() is called when exiting this scope
}
console.log("Chrome released!");

If you were to add types, it would look like this:

async function useBrowserContext(): Promise<AsyncDisposable & {
  browser: puppeteer.Browser;
  page: puppeteer.Page;
}> {
///...
}

It is an unfamiliar syntax, so it feels like a bit of a brain teaser, but once you understand the mechanism, you can recognize it as "scheduling the release process at the time of resource allocation."

I have known about its existence, but I was so happy to finally use it in a practical scenario that I decided to write an article. It is good to try out these new features early so you are not surprised when you first encounter them.

Discussion

rithmetyrithmety

この記事の try finally 版だと puppeteer.launch に失敗したら代入もされないので let を使う必要がなく
await using 版だと browser.pages にコケた場合の挙動が元コードと異なるように思います

それはそれとして using を使っていると
開放に失敗する可能性がある値を複数使う場合に特に役に立ちます

const open = name => {
  const close = () => {
    console.log(`try to close ${name}.`)
    throw new Error(`failed closing ${name}.`)
  }
  return { name, close, [Symbol.dispose]: close }
}

// 今まで
let a, b, c
try {
  a = open('a')
  try {
    b = open('b')
    try {
      c = open('c')
      console.log(a, b, c) // a,b,c を使った処理
    } finally {
      c?.close()
    }
  } finally {
    b?.close() // c の close に失敗しても b の close に挑戦する
  }
} finally {
  a?.close()
}


// これから
using a = open('a')
using b = open('b')
using c = open('c')
console.log(a, b, c) // a,b,c を使った処理
2