- 循环等待
在异步函数中,有时需要在同步 for 循环中使用异步(非同步)函数。
async function process(array) {
for (const i of array) {
await doSomething(i);
}
}
async function process(array) {
array.forEach(async i => {
await doSomething(i);
});
}
上面的代码不会像预期的那样输出期望的结果。
for
循环本身还是同步的,会在循环中的异步函数完成之前执行整个for
循环,然后将里面的异步函数逐一执行。
ES9 增加了异步迭代器,允许 await
与 for
循环一起使用,逐步执行异步操作。
async function process(array) {
for await (const i of array) {
doSomething(i);
}
}
promise.finally()
无论是成功(.then()
)还是失败(.catch()
),Promise
后面都会执行的部分。Rest, Spread
在 ES2015 中,Rest
不定长度参数…,可以转换成数组传入。- 正则表达式组
RegExp 可以返回匹配的数据包
const regExpDate = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;
const match = regExpDate.exec('2020-06-25');
const year = match[1]; // 2020
const month = match[2]; // 06
const day = match[3]; // 25
- 正则表达式 dotAll
.
表示匹配除输入以外的任何符号,添加这些标志后,允许匹配输入。
/hello.world/.test('hello\nworld'); // false
/hello.world/s.test('hello\nworld'); // true
六、ES10 (ES2019)
- 更友好的
JSON.stringify
如果输入是Unicode
但超出范围,则JSON.stringify
最初会返回格式错误的Unicode
字符串。
现在是第 3 阶段的提案,使其成为有效的 Unicode
并以 UTF-8
呈现。
Array.prototype.flat() & Array.prototype.flatMap()
展平阵列String.prototype.trimStart()
&String.prototype.trimEnd()
trimStart()
方法从字符串的开头删除空格,trimLeft()
是此方法的别名。