异步编程。
var p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("1"), 101) }) var p2 = new Promise((resolve, reject) => { setTimeout(() => resolve("2"), 100) }) Promise.race([p1, p2]).then((res) => { console.log(res) }) Promise.all([p1, p2]).then((res) => { console.log(res) })结果:
res -> 2 res -> ["1","2"] 快速的 Promise var p1 = Promise.resolve("1") var p2 = Promise.reject("2") Promise.race([p1, p2]).then((res) => { console.log(res) })结果:
res -> 1 快速失败如果一个 promise 失败,all和race也将 reject(拒绝)。
var p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("1"), 1001) }) var p2 = new Promise((resolve, reject) => { setTimeout(() => reject("2"), 1) }) Promise.race([p1, p2]).then((res) => { console.log("success" + res) }, res => { console.log("error " + res) }) Promise.all([p1, p2]).then((res) => { console.log("success" + res) }, res => { console.log("error " + res) })结果:
"error " + res -> error 2 "error " + res -> error 2 反射(Reflect)新类型的元编程与新的API现有的还有一些新的方法。
var z = {w: "Super Hello"} var y = {x: "hello", __proto__: z}; console.log(Reflect.getOwnPropertyDescriptor(y, "x")); console.log(Reflect.has(y, "w")); console.log(Reflect.ownKeys(y, "w")); console.log(Reflect.has(y, "x")); console.log(Reflect.deleteProperty(y,"x")) console.log(Reflect.has(y, "x"));结果:
Reflect.getOwnPropertyDescriptor(y, "x") -> {"value":"hello","writable":true,"enumerable":true,"configurable":true} Reflect.has(y, "w") -> true Reflect.ownKeys(y, "w") -> ["x"] Reflect.has(y, "x") -> true Reflect.deleteProperty(y,"x") -> true Reflect.has(y, "x") -> false 尾调用(Tail Call)优化尾调用的概念非常简单,一句话就能说清楚,就是指某个函数的最后一步是调用另一个函数。
ES6可以确保尾调用不会造成堆栈溢出。 (不是所有的实现工作)。
function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc); } console.log(factorial(10)) console.log(factorial(100)) console.log(factorial(1000)) console.log(factorial(10000)) console.log(factorial(100000)) console.log(factorial(1000000))结果:
factorial(10) -> 3628800 factorial(100) -> 9.332621544394418e+157 factorial(1000) -> Infinity factorial(10000) -> Infinity factorial(100000) -> RangeError: Maximum call stack size exceeded factorial(1000000) -> RangeError: Maximum call stack size exceeded原文:ES6 Features
您可能感兴趣的文章: