TypeScript中的IDisposable / RAII?

问题描述 投票:0回答:2

在TypeScript中实现确定性清理的惯用方法是什么?换句话说,是否有相当于C#的using (IDisposable)或C ++的RAII?

或者我应该坚持finally


上下文:在SPA应用程序(Aurelia / ASP.NET Core Web API)中,我试图向用户指示当前正从Web API获取数据。提取完成后,即使抛出异常,我也想删除UI指示。我正在考虑将其包装到“RAII类”中以便重用和更清晰的语法(所以我不必用finally来编写代码)...

typescript
2个回答
0
投票

在Typescript中没有using语句,你可以随时回到try-finally,这就是using在C#中的语法糖。

另一种方法是用函数创建自己的using

interface IDisposable {
    dispose();
}

function using<T extends IDisposable,
    T2 extends IDisposable,
    T3 extends IDisposable>(disposable: [T, T2, T3], action: (r: T, r2: T2, r3: T3) => void);
function using<T extends IDisposable, T2 extends IDisposable>(disposable: [T, T2], action: (r: T, r2: T2) => void);
function using<T extends IDisposable>(disposable: T, action: (r: T) => void);
function using(disposable: IDisposable[], action: (...r: IDisposable[]) => void)
function using(disposable: IDisposable | IDisposable[], action: (...r: IDisposable[]) => void) {
    let disposableArray = disposable instanceof Array ? disposable : [disposable];
    try {
        action(...disposableArray);
    } finally {
        disposableArray.forEach(d => d.dispose());
    }
}


// Usage
class UserNotify { dispose() { console.log("Done"); } }

class Other { dispose() { console.log("Done Other"); } }

using(new UserNotify(), userNotify => {
    console.log("DoStuff");
})
// It will type the arrow function parameter correctly for up to 3 parameters, but you can add more overloads above.
using([new UserNotify(), new Other()], (userNotify, other) => {
    console.log("DoStuff");
})

如果你想将它与promises一起使用,你可以创建一个异步版本,其中一次性返回一个promise,action参数也返回一个promise:

interface IDisposableAsync {
    dispose(): Promise<void> | void;
}
function usingAsync<T extends IDisposableAsync, T2 extends IDisposableAsync, T3 extends IDisposableAsync>(disposable: [T, T2, T3], action: (r: T, r2: T2, r3: T3) => Promise<void>): Promise<void>;
function usingAsync<T extends IDisposableAsync, T2 extends IDisposableAsync>(disposable: [T, T2], action: (r: T, r2: T2) => Promise<void>): Promise<void>;
function usingAsync<T extends IDisposableAsync>(disposable: T, action: (r: T) => Promise<void>): Promise<void>;
function usingAsync(disposable: IDisposableAsync[], action: (...r: IDisposableAsync[]) => Promise<void>): Promise<void>
async function usingAsync(disposable: IDisposableAsync | IDisposableAsync[], action: (...r: IDisposableAsync[]) => Promise<void>): Promise<void> {
    let disposableArray = disposable instanceof Array ? disposable : [disposable];
    try {
        await action(...disposableArray);
    } finally {
        for (let d of disposableArray) {
            let result = d.dispose();
            if (result !== null) {
                await result;
            }
        }
    }
}

// Usage
class UserNotify { dispose() { console.log("Done"); } }
class Other { dispose() { console.log("Done Other"); } }
function delay() {
    return new Promise((r)=> setTimeout(() => {
        r();
    }, 100));
}
(async function () {
    await usingAsync(new UserNotify(), async userNotify => {
        await delay()
        console.log("DoStuff");
    })

    await usingAsync([new UserNotify(), new Other()], async (userNotify, other) => {
        await delay()
        console.log("DoStuff");
    })
})();

0
投票

不幸的是,它没有语言陈述(如析构函数和确定性破坏)。你必须使用try { ... } finally { ... }语句。

如果您想知道如何以类似于C ++的方式完成它,请在我尝试使用RAII容器和TypeScript装饰器时查看https://github.com/cardinalby/ts-raii-scope。但我不确定它对生产代码有好处,因为其他开发人员可能会对这种方法感到困惑。

我认为它可以由TypeScript transforms实施

© www.soinside.com 2019 - 2024. All rights reserved.