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语句中进行数据库的关闭,这对管理文件句柄、数据库连接等资源时非常有用。

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

posted @ 2023-06-27 21:57  chuckQu  阅读(310)  评论(0编辑  收藏  举报