五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

TypeScript又出新關鍵字了?

2023-06-28 07:02 作者:吳小敏63  | 我要投稿

TypeScript 5.2將引入一個新的關鍵字:using。當它離開作用域時,你可以用Symbol.dispose函數(shù)來處置任何東西。

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

這是基于TC39提議,該提議最近達到了第三階段,表明它即將進入JavaScript。

using將對管理文件句柄、數(shù)據(jù)庫連接等資源非常有用。

Symbol.dispose

Symbol.dispose是JavaScript中一個新的全局symbol。任何具有分配給Symbol.dispose函數(shù)的東西都將被視為"資源":也就是具有特定生命周期的對象。并且該資源可以使用using關鍵字。

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

await using

你也可以使用Symbol.asyncDisposeawait來處理那些需要異步處置的資源。

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

這將在繼續(xù)之前等待Symbol.asyncDispose函數(shù)。

這對數(shù)據(jù)庫連接等資源來說很有用,你要確保在程序繼續(xù)前關閉連接。

使用案例

文件句柄

通過節(jié)點中的文件處理程序訪問文件系統(tǒng),使用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!

數(shù)據(jù)庫連接

管理數(shù)據(jù)庫連接是在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!

圖片示例

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

總結(jié)

本文簡要介紹了TypeScript5.2中引入的新關鍵字using,它的出現(xiàn)可以很好的和Symbol.dispose搭配使用。有了它我們便不需要在try…catch語句中進行數(shù)據(jù)庫的關閉,這對管理文件句柄、數(shù)據(jù)庫連接等資源時非常有用。


TypeScript又出新關鍵字了?的評論 (共 條)

分享到微博請遵守國家法律
获嘉县| 昭觉县| 永济市| 安多县| 万源市| 都匀市| 郁南县| 盘山县| 双柏县| 理塘县| 枣庄市| 白水县| 南雄市| 财经| 吴堡县| 武定县| 科尔| 湖北省| 中宁县| 逊克县| 郑州市| 辛集市| 厦门市| 芜湖市| 南木林县| 梁平县| 九龙坡区| 澄城县| 廉江市| 寻乌县| 武冈市| 仙游县| 甘南县| 绥阳县| 天峨县| 达拉特旗| 调兵山市| 荃湾区| 修武县| 乌鲁木齐县| 株洲市|