TypeScript 5.2 的新关键字:「using」
source link: https://blog.p2hp.com/archives/11203
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
本文翻译自 typescript-5-2-new-keyword-using,版权归原作者所有。
TypeScript 5.2 将引入一个新的关键字 —— 「using」,它的作用是:当离开作用域时,你可以使用 Symbol.dispose
释放掉任何内容。
{
const getResource = () => {
return {
[Symbol.dispose]: () => {
console.log('Hooray!')
}
}
}
using resource = getResource();
} // 'Hooray!' logged to console
这个功能基于最近达到第 3 阶段的TC39 提案,表明它即将进入 JavaScript。
using
对于管理文件处理、数据库连接等资源非常有用。
Symbol.dispose
Symbol.dispose
是 JavaScript 中的一个新的全局符号。任何带有 Symbol.dispose
功能的都被视为“资源”—— “具有特定生命周期的对象” ——并且可以与关键字 using
一起使用。
const resource = {
[Symbol.dispose]: () => {
console.log("Hooray!");
},
};
await using
您还可以使用 Symbol.asyncDispose
and await using
来处理需要异步处理的资源。
const getResource = () => ({
[Symbol.asyncDispose]: async () => {
await someAsyncFunc();
},
});
{
await using resource = getResource();
}
这将在继续之前等待 Symbol.asyncDispose
函数。
这对于数据库连接等资源很有用,例如您希望在这些资源中确保连接在程序继续运行之前关闭。
没有 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 = getFileHandle("thefile.txt");
// Do stuff with file.filehandle
} // Automatically disposed!
数据库连接
使用 using
管理数据库连接是 C#
中的一个常见用例。
没有 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 { connection } = getConnection();
// Do stuff with connection
} // Automatically closed!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK