用npm下載KOA npm
就會在koa文件夾下生成app
我下載的KOA版本號是2.0.1koa
const Koa = require('koa'); const app = new Koa(); // response app.use(ctx => { ctx.body = 'Hello Koa'; }); app.listen(3000);
必定注意版本號1.2,應該是這樣寫的異步
let koa = require('koa'); let app = koa(); app.use(function*(){ this.body = "hello xiaomo"; }); app.listen(8080);
剛開始我下載的是2.0版倒是照着1.2版本的代碼寫的會報錯。async
關鍵詞 function*。這個星號表示這個函數是一個生成器函數。這意味着這個函數能夠在運行的時候跳出而後再跳回來。這個概念很難去表述,因此我給你舉個栗子。函數
function* inc () { let number = 0 while (true) yield number++ } let test = inc() console.log(test.next().value) // -> 0 console.log(test.next().value) // -> 1 console.log(test.next().value) // -> 2
我分解一下這個程序:ui
inc 函數定義了一個生成器函數,在每一次 while 循環中,產出 number 變量而後 number 變量加 1inc 函數被指派給了變量 testthis
inc 函數被迭代了 3 次,第一次的時候,number 變量在函數中被初始化了。而後,這個函數進入到了一個 while 循環,在以後的迭代中這個循環也不會退出。而後 number 0 被產出,因此這個能夠用 .value 方法接收。在後來的迭代中這個變量 number 自增了兩次。url
我但願這能夠幫助理解一點生成器的工做原理。這只是很是複雜的 ES6 中的一小部分。spa
可是不管如何,讓咱們回到 koa。koa 很是簡單,甚至不包含一個路由。你須要在中間件生成器函數中手動作路由匹配:
請求先通過 x-response-time
和 logging
中間件,並記錄中間件執行起始時間。 而後將控制權交給 reponse
中間件。當中間件運行到 yield next
時,函數掛起並將控制前交給下一個中間件。當沒有中間件執行 yield next
時,程序棧會逆序喚起被掛起的中間件來執行接下來的代碼。
ES7(目前是草案,尚未發佈)引入了新的關鍵字async
和await
,能夠輕鬆地把一個function變爲異步模式:
const Koa = require('koa'); const app = new Koa(); // x-response-time app.use(async function (ctx, next) { const start = new Date(); await next(); const ms = new Date() - start; ctx.set('X-Response-Time', `${ms}ms`); }); // logger app.use(async function (ctx, next) { const start = new Date(); await next(); const ms = new Date() - start; console.log(`${ctx.method} ${ctx.url} - ${ms}`); }); // response app.use(ctx => { ctx.body = 'Hello World'; }); app.listen(3000);
在KOA1.0時實現異步,是這樣實現的。
var koa = require('koa'); var app = koa(); app.use('/test', function *() { yield doReadFile1(); var data = yield doReadFile2(); this.body = data; }); app.listen(3000);
在KOA2.0是這樣實現的
app.use(async (ctx, next) => { await next(); var data = await doReadFile(); ctx.response.type = 'text/plain'; ctx.response.body = data; });
參考:http://www.tuicool.com/articles/EnuiIj