typescript using 教程

关于资源管理,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 方法。保证资源的释放。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一拖再拖 一拖再拖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值