Featured image of post ECMAScript 2025 (ES16) 中令人興奮的功能Featured image of post ECMAScript 2025 (ES16) 中令人興奮的功能

ECMAScript 2025 (ES16) 中令人興奮的功能

預覽一下 ECMAScript 2025 中即將推出的標準 API 提案,其中詳細介紹了 Promise.try、Iterator Helpers 和本機 Set 操作。

介紹

每年,TC39 委員會都會更新 ECMAScript 規範,為 JavaScript 生態系引進新的語言功能和 API。

對於即將推出的 ECMAScript 2025 (ES16) 標準,一些提案已達到第 3 階段或第 4 階段,表明它們正處於瀏覽器實施和採用的最後階段。

本文重點介紹了 ES2025 中的一些新功能,詳細介紹了它們如何簡化編碼模式。


1. Promise.try:統一同步與非同步錯誤處理

JavaScript 開發的常見挑戰是以乾淨、統一的方式處理同步異常和非同步 Promise 拒絕。

為了解決這個問題,TC39 委員會引入了 Promise.try()

挑戰

當呼叫可能拋出同步異常或傳回被拒絕的 Promise 的函數 runTask 時,要乾淨地處理這兩種錯誤類型可能很困難。

// Handling both error types requires redundant boilerplate
function handleTask(runTask) {
  try {
    const result = runTask();
    if (result instanceof Promise) {
      result.catch(err => console.error("Async error:", err));
    }
  } catch (err) {
    console.error("Sync error:", err);
  }
}

使用 Promise.try 進行乾淨的實現

Promise.try() 執行傳遞的回呼。如果回呼拋出同步異常,則 Promise.try() 捕獲異常並傳回 rejected Promise。這允許您連結單一 .catch() 處理程序來捕獲同步和非同步錯誤。

function handleTask(runTask) {
  Promise.try(runTask)
    .then(result => console.log("Result:", result))
    .catch(err => console.error("Unified error handler:", err));
}

2. 迭代器助手:迭代器上的映射與篩選

儘管陣列本身支援 .map().filter(),但 JavaScript Map 和 Set 迭代器(如 .keys().values())歷來缺乏這些方法。

ES2025 透過引入 Iterator Helpers 來解決這個問題,它為所有迭代器物件帶來實用方法。

程式碼範例

const mySet = new Set([1, 2, 3, 4, 5]);

// Chain filter and map directly on the Set iterator
const processed = mySet.values()
  .filter(x => x % 2 !== 0) // Keep only odd numbers
  .map(x => x * 10);        // Multiply by 10

for (const value of processed) {
  console.log(value); // Outputs: 10, 30, 50
}
  • 惰性評估: 迭代器助理使用惰性求值,這意味著僅在請求時才處理項目。這允許您處理大型資料集或無限流,而無需為中間數組分配記憶體。

3. 標準集合運算

本機 JavaScript Set 類別接收支援標準數學集合運算的更新。

開發人員現在可以使用本機輔助方法來運行這些操作,而不是編寫自訂循環來計算並集和交集。

新的設定方法

  • union():傳回一個包含兩個集合中所有元素的集合。
  • intersection():傳回僅包含兩個集中都存在的元素的集合。
  • difference():傳回一個集合,其中包含第一個集合中存在的元素,但不包含第二個集合中的元素。
  • symmetricDifference():傳回一個集合,其中包含任一集合中存在的元素,但不是同時存在於兩個集合中。

程式碼範例

const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);

// Calculate the intersection (common elements)
const common = setA.intersection(setB);
console.log(common); // Set { 3 }

// Calculate the union (all unique elements)
const combined = setA.union(setB);
console.log(combined); // Set { 1, 2, 3, 4, 5 }

結論和瀏覽器支持

ECMAScript 2025 中的新 API 以直接內建於瀏覽器 JavaScript 引擎中的本機優化實作取代了自訂幫助程式庫(如 Lodash)。

這些提案中的大多數已經在 Chrome、Edge 和 Safari 的實驗版或測試版中實現,並且可以透過更新 Babel 或 TypeScript 轉譯目標來用於開發。

為這些即將到來的標準添加做好準備,以編寫更乾淨、更有效率的 JavaScript。