TypeScript 相当于 Go 的 Defer 语句

dak*_*aka 7 typescript

TypeScript 有类似 Go 的Defer语句吗?

我厌倦了在整个函数的多个位置编写清理代码。寻找更简单的解决方案。

我快速谷歌了一下,但没有找到任何东西。

T.J*_*der 5

可以说答案是否定的,但您至少有几个选择:

  1. 正如@bereal 提到的,你可以使用try/finally来实现这一点。回复try/ finally,在评论中你说:

    是的,除了我不想使用 try catch 块,因为它们可能很昂贵。

    并不真地。抛出一个Error是昂贵的(昂贵的是创建,填充堆栈信息;实际抛出它并不花费太多);进入try区块则不然。在 JavaScript 中,你不必抛出实例Error,你可以抛出任何东西;如果你想在不填写堆栈信息的情况下抛出,你可以抛出一个非Error(尽管我不提倡这样做)。单独地,finally块有轻微的开销,但碰巧我最近不得不在几个现代引擎中测量它,这确实是令人惊讶的微不足道。

  2. 您可以将函数分配给变量,然后在函数末尾运行它(或者如果您想要执行多个操作,则可以使用数组)。对于单次清理,我预计它会比try/更昂贵finally。对于多个(否则需要嵌套try/finally块),那么,您必须找出答案。

FWIW,一些例子:

try/中的一次清理finally

function example() {
    try {
        console.log("hello");
    } finally {
        console.log("world");
    }
}
example();
Run Code Online (Sandbox Code Playgroud)

try/中的多次清理finally

function example() {
    try {
        console.log("my");
        try {
            console.log("dog");
        } finally {
            console.log("has");
        }
    } finally {
        console.log("fleas");
    }
}
example();
Run Code Online (Sandbox Code Playgroud)

通过分配函数进行单一清理:

function example() {
    let fn = null;
    fn = () => console.log("world");
    console.log("hello");
    if (fn) { // Allowing for the above to be conditional, even though
              // it isn't above
        fn();
    }
}
example();
Run Code Online (Sandbox Code Playgroud)

try/中的多次清理finally

function example() {
    const cleanup = [];
    cleanup.push(() => console.log("has"));
    console.log("my");
    cleanup.push(() => console.log("fleas"));
    console.log("dog");
    cleanup.forEach(fn => fn());
}
example();
Run Code Online (Sandbox Code Playgroud)

或者按照其他顺序:

function example() {
    const cleanup = [];
    cleanup.push(() => console.log("fleas"));
    console.log("my");
    cleanup.push(() => console.log("has"));
    console.log("dog");
    while (cleanup.length) {
        const fn = cleanup.pop();
        fn();
    }
}
example();
Run Code Online (Sandbox Code Playgroud)