关于资源管理,typescript新增了using声明。
在过去,我们为了确保资源的清理,常常使用try…finally,而using的出现大大提高了代码的可读性和可维护性,简化了资源管理。
版本要求
- Node.js: >= 20
- TypeScript: >= 5.2
如果您出现 TypeError: Symbol.dispose is not defined. 类似的错误,请更新你的node版本。
使用场景:管理一些资源,如文件、网络连接或内存。这些资源在使用完毕后通常需要进行清理,以避免资源泄漏或其他问题。
using的优点:
- 简洁性:使用using可以避免try/catch/finally的使用,使代码更加简洁。
- 自动清理:using可以自动调用资源的dispose方法,避免资源泄漏。
- 错误处理:如果作用域内发生错误(抛出异常等),using 声明还将确保资源被正确清理。
- 可读性和维护性:using可以使代码更加简洁,更加容易阅读和维护。
- 灵活性:using可以用于同步和异步代码。
1:定义 Disposable
class TempFile implements Disposable {
[Symbol.dispose]() {
console.log("Deleting temporary file...");
}
}
定义好之后我们就可以使用 using
来使用了
function doSomeWork() {
using _ = new TempFile();
return;
}
当函数执行完毕之后,using
会自动调用 dispose
方法,释放资源。
2:用于异步的 using
class AsyncTempFile implements AsyncDisposable {
type: string;
constructor(type) {
console.log(`Creating ${type} file...`);
this.type = type;
}
async [Symbol.asyncDispose]() {
console.log(`Deleting ${this.type} file...`);
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
async function doSomeWork() {
await using a = new AsyncTempFile('1');
await using b = new AsyncTempFile('2');
await using c = new AsyncTempFile('3');
return;
}
3:using执行顺序
using执行顺序遵循栈的规则,先进后出。
function tempFile(type: string) {
return {
[Symbol.dispose]() {
console.log(`Disposing ${type} file!`);
}
}
}
function func() {
using a = tempFile('1')
using b = tempFile('2')
using c = tempFile('3')
}
func()
输出结果:
Disposing 3 file!
Disposing 2 file!
Disposing 1 file!
4:using的错误处理
function tempFile(type: string) {
return {
[Symbol.dispose]() {
console.log(`Disposing ${type} file!`);
}
}
}
function func() {
using a = tempFile('1')
throw new Error('error2')
}
func()
输出结果:
Disposing 1 file!
throw env.error.............................
即使在出现错误时,也会自动调用 dispose
方法。保证资源的释放。