gpt4 book ai didi

相当于 Go 的 Defer 语句的 TypeScript

转载 作者:行者123 更新时间:2023-12-04 17:29:45 24 4
gpt4 key购买 nike

TypeScript 有没有类似于 Go 的 Defer陈述?

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

我已经做了一个快速的谷歌,但没有找到任何东西。

最佳答案

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

  • 正如@bereal 提到的,你会使用 try/finally为了那个原因。回复 try/finally ,在评论中你说:

    Yep, except I don't want to use a try catch block as they can be expensive.



    并不真地。抛出异常代价高昂;输入 try块不是。 finally块有轻微的开销,但碰巧我最近不得不在几个现代引擎中测量它,这确实非常简单。
  • 您可以将一个函数分配给一个变量,然后在该函数的末尾运行它(或者,如果您想执行多个操作,也可以使用一个数组)。对于单次清理,我预计它会比 try 贵/finally .对于多个(否则需要嵌套的 try/finally 块),好吧,您必须找出答案。

  • FWIW,一些例子:
    try 中的单个清理/ finally :

    function example() {
    try {
    console.log("hello");
    } finally {
    console.log("world");
    }
    }
    example();


    多次清理 try/ finally :

    function example() {
    try {
    console.log("my");
    try {
    console.log("dog");
    } finally {
    console.log("has");
    }
    } finally {
    console.log("fleas");
    }
    }
    example();


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

    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();


    多次清理 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();


    或者按其他顺序:

    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();

    关于相当于 Go 的 Defer 语句的 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60847836/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com