文章预览
JavaScript 语言标准 ECMAScript 2025 候选版已于 3 月发布,正式版预计 6 月落地。 此次更新聚焦开发者痛点,从正则处理到异步编程均有实用性改进,以下选取核心特性展开分析,新功能一览: Promise 和迭代器改进 Promise.try Promise.try(fn) 用于将函数 fn 包装成 Promise,同步执行并处理异常,统一同步和异步行为。 以前,处理可能同步或异步的函数需要 Promise.resolve().then(fn) ,但这异步执行,影响性能;或用 new Promise(resolve => resolve(fn())) ,代码冗长。 function mightThrow() { if (Math .random () > 0.5 ) throw new Error("Oops"); return "Success"; } Promise .resolve () .then (mightThrow) .then (result => console .log (result)) .catch (error => console .error (error)); 在 ES2025 中可以这样: Promise .try (mightThrow) .then (result => console .log (result)) .catch (error => console .error (error)); 同步迭代器辅助
………………………………