[Javascript] Highlights from IO18 Javascript new features

本文介绍了最新的JavaScript特性,包括异步函数中的try-catch-finally模式、Promise的finally方法、正则表达式的前瞻与回顾功能以及使用JavaScript模块的方式。通过示例展示了如何在实际应用中运用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Latest Javascript features, not supported by all broswers, but can use with babel.

 

# try-catch-finally, Promise finally:

async function fetchAndDisplay({url, element}) {
    
    showLoadingSpinner();
    try {
        const response = await fetch(url);
        const text = await response.text();
        element.textContent = text;
    } catch(error) {
         element.textContent = error.message;
    } finally {
        hideLoadingSpinner();
   }
}
function getStarsNumber(username, reponame) {
    startLoadingAnimation();

    return fetch(`https://api.github.com/repos/${username}/${reponame}`)
        .then(res => res.json())
        .then(data => data.stargazers_count)
        .catch(() => `Couldn't get the stars number`)
        .finally(stopLoadingAnimation);
}

 

# Regex:

1. Lookbehind:

// Positive lookbehind:
const partten = /(?<=\$)\d+/u; //looking for any number after  $ 
const res = pattern.exec('$42');
// res[0] === '42'

// Negative lookbehind:
const pattern = /(?>!\$)\d+/u; // looking for any number which is not after $
const res  = pattern.exec('£42');
// res[0] === '42'

 

2. Lookahead:

// Positive lookahead:
const pattern = /\d+(?= dollars)/u; // looking for any number before dollars
const res = pattern.exec('42 dollars');
// res[0] === '42'

// Negative lookahead:
const pattern = /\d+(?! dollars)/u; // looking for any number which is not before dollars
const res = pattern.exec('42 rupees');
// res[0] === '42'

 

3. Named group catch:

const pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
const res = pattern.exec('2018-05-09');;

// res.group.year === '2018'
// res.group.month === '05'
// res.group.day === '09'

 

4. Find whole words with line break:

using: 's', pretty much you can add 'us' to all regex.

 

# Javascript module:

<link rel = "modulepreload" href="lib.mjs">  <!-- preload module -->
<link rel = "modulepreload" href="main.mjs">
<script type="module" src="main.mjs"></script> <!-- javascript module file-->
<script nomodule src="fallback.js"></script> <!-- fallback to normal js file -->

 

Talk

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值