• TypeScript又出新关键字了?


    TypeScript 5.2将引入一个新的关键字:using。当它离开作用域时,你可以用Symbol.dispose函数来处置任何东西。

    {
      const getResource = () => {
        return {
          [Symbol.dispose]: () => {
            console.log('Hooray!')
          }
        }
      }
      using resource = getResource();
    } // 'Hooray!' logged to console
    

    这是基于TC39提议,该提议最近达到了第三阶段,表明它即将进入JavaScript。

    using将对管理文件句柄、数据库连接等资源非常有用。

    Symbol.dispose

    Symbol.dispose是JavaScript中一个新的全局symbol。任何具有分配给Symbol.dispose函数的东西都将被视为"资源":也就是具有特定生命周期的对象。并且该资源可以使用using关键字。

    const resource = {
      [Symbol.dispose]: () => {
        console.log("Hooray!");
      },
    };
    

    await using

    你也可以使用Symbol.asyncDisposeawait来处理那些需要异步处置的资源。

    const getResource = () => ({
      [Symbol.asyncDispose]: async () => {
        await someAsyncFunc();
      },
    });
    {
      await using resource = getResource();
    }
    

    这将在继续之前等待Symbol.asyncDispose函数。

    这对数据库连接等资源来说很有用,你要确保在程序继续前关闭连接。

    使用案例

    文件句柄

    通过节点中的文件处理程序访问文件系统,使用using可能会容易得多。

    不使用using

    import { open } from "node:fs/promises";
    let filehandle;
    try {
      filehandle = await open("thefile.txt", "r");
    } finally {
      await filehandle?.close();
    }
    

    使用using

    import { open } from "node:fs/promises";
    const getFileHandle = async (path: string) => {
      const filehandle = await open(path, "r");
      return {
        filehandle,
        [Symbol.asyncDispose]: async () => {
          await filehandle.close();
        },
      };
    };
    {
      await using file = getFileHandle("thefile.txt");
      // Do stuff with file.filehandle
    } // Automatically disposed!
    

    数据库连接

    管理数据库连接是在C#中使用using的一个常见用例。

    不使用using

    const connection = await getDb();
    try {
      // Do stuff with connection
    } finally {
      await connection.close();
    }
    

    使用using

    const getConnection = async () => {
      const connection = await getDb();
      return {
        connection,
        [Symbol.asyncDispose]: async () => {
          await connection.close();
        },
      };
    };
    {
      await using { connection } = getConnection();
      // Do stuff with connection
    } // Automatically closed!
    

    图片示例

    下图是上面示例的图片版本:

    await-using.jpg

    总结

    本文简要介绍了TypeScript5.2中引入的新关键字using,它的出现可以很好的和Symbol.dispose搭配使用。有了它我们便不需要在try…catch语句中进行数据库的关闭,这对管理文件句柄、数据库连接等资源时非常有用。

    以上就是本文的全部内容,如果对你有所启发,欢迎点赞、收藏、转发~

  • 相关阅读:
    【每日一题】搜索二叉树的最大拓扑结构
    巨额亏损,股价遭受重创,Polestar极星汽车已陷入困境
    考虑温度影响的vumat子程序在木材受火后强度分析中的应用
    Linux文件编程(lseek函数和stat函数)
    解决from d2l import torch as d2l报pandas,numpy的相关问题
    【EI会议征稿】第四届环境资源与能源工程国际学术会议(ICEREE 2024)
    centos安装mysql8.0.20、tar包安装方式
    ant的FileSet资源集合
    新的LLM 评价方法优化
    stm32驱动GC9A01显示(整理有stm32/51单片机/arduino等驱动代码)
  • 原文地址:https://www.cnblogs.com/chuckQu/p/17510044.html