TypeScript 5.2 引入了一个新的关键字 —— using
—— 你可以用它来处理任何带有 Symbol.dispose
函数的代码,在当它离开作用域时,作一些自动操作。
{
const getResource = () => {
return {
[Symbol.dispose]: () => {
console.log('Hooray!')
}
}
}
using resource = getResource();
} // 'Hooray!' logged to console
这是基于TC39的提案,最近在JavaScript的进展中达到了阶段3(共4个阶段),这意味着它已经准备好由早期采用者进行测试。
using
对于管理文件句柄、数据库连接等资源非常有用。
Symbol.dispose
Symbol.dispose
是 JavaScript 中的一个新的全局符号,任何具有 Symbol.dispose
函数的元素都被认为是一个“资源”——“具有特定生命周期的对象”——并且可以与 using
关键字一起使用。
const resource = {
[Symbol.dispose]: () => {
console.log("Hooray!");
},
};
await using
你也可以使用 Symbol.asyncDispose
和 await using
来处理需要异步处理的资源。
const getResource = () => ({
[Symbol.asyncDispose]: async () => {
await someAsyncFunc();
},
});
{
await using resource = getResource();
}
这将在继续之前等待 Symbol.asyncDispose
函数。
这对于数据库连接等资源很有用,在这些资源中,您希望确保在程序继续之前关闭连接。
用例
文件句柄
使用 using
可以更容易地通过 node 中的文件处理程序访问文件系统。
没有 using
:
import { open } from "node:fs/promises";
let filehandle;
try {
filehandle = await open("thefile.txt", "r");
} finally {
await filehandle?.close();
}
与有 using
:
import { open } from "node:fs/promises";
const getFileHandle = async (path: string) => {
const filehandle = await open(path, "r");
return {
filehandle,
[Symbol.asyncDispose]: async () => {
await filehandle.close();
},
};
};
{
await using file = await getFileHandle("thefile.txt");
// Do stuff with file.filehandle
} // Automatically disposed!
数据库连接
管理数据库连接是 using
的常见用例。
没有 using
:
const connection = await getDb();
try {
// Do stuff with connection
} finally {
await connection.close();
}
与有 using
:
const getConnection = async () => {
const connection = await getDb();
return {
connection,
[Symbol.asyncDispose]: async () => {
await connection.close();
},
};
};
{
await using db = await getConnection();
// Do stuff with db.connection
} // Automatically closed!
欢迎关注公众号:文本魔术,了解更多