原文:ES2020
1.class中的私有变量
class Message {
#message = "Howdy"
greet() { console.log(this.#message) }
}
const greeting = new Message()
greeting.greet() // Howdy
console.log(greeting.#message) // Private name #message is not defined
2.Promist.allSetted
Promise.all 和 Promise.allSettled
由于单一 Promise 进入 rejected 状态便会立即让 Promise.all() 的结果进入 rejected 状态,以至于通过 Promise.all() 进入 rejected 状态时,其中的源 Promise 仍然可能处于 pending 状态,以至于无法获得所有 Promise 完成的时机。
Promise.allSettled() API 被提出,其中 settled 状态的定义是非 pending,即 fulfilled 或者 rejected 中的任一状态。
Promise 中的三兄弟 .all(), .race(), .allSettled()
Promise.all()的类型签名:
Promise.all<T>(promises: Iterable<Promise<T>>): Promise<Array<T>>
返回情况:
完成(Fulfillment): 如果传入的可迭代对象为空,Promise.all 会同步地返回一个已完成(resolved)状态的promise。 如果所有传入的 promise 都变为完成状态,或者传入的可迭代对象内没有 promise,Promise.all 返回的 promise 异步地变为完成。 在任何情况下,Promise.all 返回的 promise 的完成状态的结果都是一个数组,它包含所有的传入迭代参数对象的值(也包括非 promise 值)。
失败/拒绝(Rejection): 如果传入的 promise 中有一个失败(rejected),Promise.all 异步地将失败的那个结果给失败状态的回调函数,而不管其它 promise 是否完成。
3.??
let person = {
profile: {
name: "",
age: 0
}
};
console.log(person.profile.name || "Anonymous"); // Anonymous
console.log(person.profile.age || 18); // 18
console.log(person.profile.name ?? "Anonymous"); // ""
console.log(person.profile.age ?? 18); // 0
4.BigInt
原来JS的最大值为MAX_SAFE_INTEGER2^53
const max = Number.MAX_SAFE_INTEGER;
console.log(max); // 9007199254740991
现在增加BigInt,数据后面要加个n,
const bigNum = 100000000000000000000000000000n;
console.log(bigNum * 2n); // 200000000000000000000000000000n

5.可以使用 async/await 来动态引入import
import()之后返回一个Promise对象
// pages/about.js
export function render() {
// 渲染页面
}
// index.js
import('./pages/about').then(function(page) {
// 渲染页面
page.render()
})
// 或者
const page = await import('./pages/about')
// 渲染页面
page.render()
// math.js
const add = (num1, num2) => num1 + num2;
export { add};
// index.js
const doMath = async (num1, num2) => {
if (num1 && num2) {
const math = await import('./math.js');
console.log(math.add(5, 10));
};
};
doMath(4, 2);
ES2020语法新加插件
{
"plugins": [
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-private-methods",
"@babel/plugin-syntax-bigint"
]
}