菜神 @fundon 大晚上不睡觉,放毒:https://github.com/pauliusuza/node-v7-async-await-demo?utm_content=buffer9bce9&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer 稍加整理,以便阅读node
很早以前https://nodejs.org/download/test就放出了构建好的测试版本的,咱们可使用nvm来安装。若是你们不熟悉nvm,能够参靠比较经典的Node.js的3m安装法git
第一步配置环境变量,指定nvm使用的v7 mirror,这是由于默认的nvm mirror指向的是https://nodejs.org/dist/,因此默认nvm ls-remote是查不到v7的。github
在terminal中执行,放在永久环境变量中不太必要promise
$ NVM_NODEJS_ORG_MIRROR=https://nodejs.org/download/test
而后查看一下远端版本app
$ nvm ls-remote v4.6.1 v6.7.0 v7.0.0
而后就开始Node v7吧koa
$ nvm install 7 $ nvm use 7
我在安装的时候没有成功,后来是https://nodejs.org/download/test/v7.0.0-test201610107f7d1d385d/下载的源文件安装的。异步
若是上面的不可用,能够参考评论中的https://cnodejs.org/topic/580027e20bab808265185db2#58004364fdf3bd3d651185f4async
定义class函数
// An example class which generates a hello world greeting class Demo { async greeting() { const h = await this.world(); return h; } world() { return Promise.resolve('hello world'); } }
在promise时代,要作到每一个流程函数都返回promise,而后再组装,这称为广义的promisify。如今换成async函数,主要是取决于await能组合的2种作法测试
本例中,就很是典型,在async函数greeting里经过await来执行this上下文中的world函数,很明显world是返回Promise的函数。
我以前也说过promise的重要性,几乎贯穿全部异步流程控制中。async/await时代的前期,它仍是主力,不管是已有项目-知识迁移,仍是组装和简化的便利性。
在Koa 2.x里使用
// Import Koa v2 dependency const Koa = require('koa'); // Initialize Demo class instance const demo = new Demo(); // Initialize Koa v2 instance const app = new Koa(); const port = 3000; // uses async arrow functions app.use(async (ctx, next) => { try { await next(); // wait until we execute the next function down the chain, then continue; } catch (err) { ctx.body = { message: err.message }; ctx.status = err.status || 500; } }); // Set up a route app.use(async ctx => { const retval = await demo.greeting(); ctx.body = retval; }); // Start listening on specified port app.listen(port, function() { console.log("listening on port", port); }); // Start the app with "node --harmony-async-await" flag, and go to http://localhost:3000
Koa 2.x的简单代码就不解释了,有疑问能够参见https://github.com/i5ting/stuq-koa
执行
$ node -v; node --harmony-async-await index.js
很明显,是经过--harmony-async-await这个flag来执行的。也就是说尚未变成内置功能。这让咱们不由想起当年generator的状况,从0.10,0.12····4.x。也就是说,变成内置还要很长时间
好在,咱们已经可以体验了,老雷说:“这几个月js发展真快啊”,起来嗨~