/*let 和 const: let用于定义一个块做用域的变量,const 定义一个常量 */ let a = 'test'; const b = 2; /*对象的属性和方法的简写: */ /* ES5写法: */ var name = 'test'; var es5Ojb = { name:name, func:function(){ } }; /* ES6对象属性和方法写法: */ var obj = { name, func(){ } }; /* 箭头函数 */ /* ES5匿名函数写法:*/ function es5Test(){ return function(){ console.log('es5Test'); }; }; /* ES6写法: */ function es6Test(){ return ()=>{ console.log('es6Test'); }; }; /* 用Promise处理回调函数*/ //ES6:函数形参的数据类型为一个函数,在函数体内调用该形参,并传参,在函数体外执行该函数,并写入函数,好比下面 var p = new Promise((reslove,reject)=>{ //模仿异步函数 setTimeout(()=>{ var name = '张三'; if(Math.random()<0.7) reslove(name); else reject('失败'); },1000); }); /* data为reslove或者reject传进的参数 */ p.then((data)=>{ console.log(data); });
/* aysnc function function_name(){} 可以将函数转为异步执行 */ async function getData(){ return '将函数转为异步执行'; }; /* 获取异步函数执行的数据,方法一: */ var p = getData(); p.then((data)=>{ console.log(data); //将函数转为异步执行 }); // 获取异步函数执行的数据,方法二:await ,可以获取等待异步函数执行,并获取异步函数里的数据,await可以将函数改成同步,await只能在异步函数里使用 async function test(){ var d = await getData(); console.log(p); }; test();// 将函数转为异步执行 //async 与 await 组合,可以在async异步函数里,使用await等待其余异步函数执行完成并来获取其余异步函数里的数据,再执行下面的语句,例: function other_async(){ //模仿异步函数 return new Promise((reslove,reject)=>{ setTimeout(()=>{ var username = '张三'; reslove(username); },1000); }); }; async function test(){ var data = await other_async(); console.log(data); }; test(); // 张三
二、koa2 安装:在文件夹内打开cmd ,输入: npm install --save koa ,注意:只有node.js版本在7.2以上才能够使用,使用 node -v 命令便可查看node版本node
const koa = require('koa'); const app = new koa(); app.use( async(ctx)=>{ ctx.body = 'hello koa2'; }); app.listen(80);
效果:es6