新的概念与方法
概略图:

基本使用
rest操作符解构赋值
- 合并数组
const [...iterableObj] = [1, 3, 5, 7, 9];
let newArr = [...iterableObj, 0, 2, 4, 6, 8];
console.log(newArr); //Array(10) [ 1, 3, 5, 7, 9, 0, 2, 4, 6, 8 ]
- 合并对象
let obj = { foo: 10, bar: 20, baz: 30 };
let {foo, ...rest} = obj;
console.log(foo); // 10
console.log(rest); // Object { bar: 2, baz: 3 }
const DEFAULTS = {foo: 'a', bar: 'b'};
const userData = {foo: 1};
const data = {...DEFAULTS, ...userData};
console.log(data); // {foo: 1, bar: 'b'}
正则扩展 具名分组
const RE_DATE = /([0-9]{4})-([0-9]{2})-([0-9]{2})/;
let matchObj = RE_DATE.exec('1999-12-31');
let year = matchObj[1]; // 1999
let month = matchObj[2]; // 12
let day = matchObj[3]; // 31
Promise 扩展方法finally, 继then、catch之后 第三个阶段函数
finally回掉会一直执行,不像then与catch只可以逻辑二选一
Promise.prototype.finally()
let connection;
db.open()
.then(conn => {
connection = conn;
return connection.select({ name: 'Jane' });
})
.then(result => {
// Process result
// Use `connection` to make more queries
})
···
.catch(error => {
// handle errors
})
.finally(() => {
connection.close();
});
for await...of
异步生成器已经实现了异步迭代器协议, 所以可以用 for await...of循环
async function* asyncGenerator() {
var i = 0;
while (i < 3) {
yield i++;
}
}
(async function() {
for await (num of asyncGenerator()) {
console.log(num);
}
})();
网友评论