iTranslated by AI
Practical Resource Disposal with await using
Practice
The "I wondered when I'd ever use this, and the day finally came" series.
I used it with Deno this time, but it also works in Node.js or browsers if you include a Polyfill.
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
僕も最近知って嬉しくなったので補足情報の共有なのですが、Playwrightの各種クラスに対しても同様に
await usingが使えます!使用例
この記事の try finally 版だと puppeteer.launch に失敗したら代入もされないので let を使う必要がなく
await using 版だと browser.pages にコケた場合の挙動が元コードと異なるように思います
それはそれとして using を使っていると
開放に失敗する可能性がある値を複数使う場合に特に役に立ちます