2017年6月底es2017不期而至; 截止目前es8是ecmascript规范的第九个版本;自es2015开始ECMA协会将每年发布一个版本并将年号作为版本号;算了 直接看下es2017的新特性:
1.异步函数
ECMAScript 2017功能“ 异步函数 ”由Brian Terlson提出。其是Generator的语法糖,简单讲就是用async关键字代替了*,用await(只能在异步函数中使用)关键字代替了yield,并且不需要next调用直接全部执行换言之没有惰性求值如下
声明:async function testAsync ( ) { return.... } // 用async 声明一个异步函数
调用:testAsync ().then( result => {....} ).catch(e => {...})//此处 result 为异步函数最终返回值 也就是上面return的值 catch用法同generator一致;
await: await 命令后面是一个 Promise 对象。如果不是,会被转成一个立即resolve的 Promise 对象, 若Promise 变为reject,则整个async函数都会中断执行,并且reject的参数会被catch捕获;
接着看代码:
function add(num){
return ++num
}
async function testAasync(num){
let a = await add(num);
let b = await add(a);
if(a!==3){
throw Error("error")
}
return {a,b};
}
testAasync(2).then(result =>{
console.log(result );// {a:3,b:4}
}).catch(e=>console.log(e));testAasync(1).then(result =>{
console.log(result );
}).catch(e=>console.log(e));// error//---------------------------------------------------------------------- async function testAasync(num){ let c = await 789;//await 后面不是promise会被转成一个立即resolve的 Promise 对象 let a = await Promise.reject('error'); console.log("这里不会打印,下面也不会执行,reject的参数被下面catch捕获并打印"); let b = await 123; return b;}testAasync(2).then(x=>{ console.log(x);}).catch( e => console.log(e) );// error