Koa是中間件通過一種更加傳統(tǒng)(您也許會很熟悉)的方式進(jìn)行級聯(lián), 摒棄了以往node頻繁的回調(diào)函數(shù)造成的復(fù)雜代碼邏輯鸣皂。我們通過generators來實現(xiàn)“真正”的中間件抓谴。
Connect簡單 地將控制權(quán)交給一系列函數(shù)來處理,直到函數(shù)返回寞缝。與之不同癌压,當(dāng)執(zhí)行yield next 語句時,Koa暫停了該中間件荆陆,繼續(xù)執(zhí)行下一個符合請求的中間件滩届,然后控制權(quán)再逐級返回給上層中間件。
下面的例子頁面返回“Hello World"被啼,然而當(dāng)請求開始時帜消, 請求經(jīng)過x-response-time和logging中間件,并記錄中間件執(zhí)行起始時間趟据。然后將控制權(quán)交給response中間件券犁。當(dāng)中間件運行到y(tǒng)ield next時,函數(shù)扶起并將控制權(quán)交給下一個中間件汹碱。當(dāng)沒有中間件執(zhí)行yield next時粘衬, 程序棧會逆序喚起被掛起的中間件來執(zhí)行接下來的代碼。
var koa = require('koa');
var app = koa();
// x-response-time
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
// logger
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
// response
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);