koa 使用的是async await等待 經典句型:await next();類似堆棧先進後出
參數(ctx, next)
express 是逐步流下去的,走到最後都不匹配,資源返回404,xhr返回500
參數(req, res, next)
源碼解讀:待補充
http.createServer(app.callback()).listen(...)
new Koa()時候自動執行了constructor,callback 方法,返回的handleRequest是function handleRequest(req, res){ ... }
npm源碼涉及模塊
..........................................................................................................................................
koa-compose模塊 作用:返回一個Promise連續調用的function(待後期使用)
關鍵點 function dispatch(i) 當未到達最後時遞歸調用 return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
很多代碼中return function出去,是爲了保存上一次傳進來的參數,備用
..........................................................................................................................................
delegates模塊,作用:事件委託,有以下5個方法,
method, access, getter, setter, fluent 分別push到對應數組,
this.methods = [];
this.getters = [];
this.setters = [];
this.fluents = [];
proto.__defineGetter__()
proto.__defineSetter__()
koa文件夾的lib/context.js中進行事件委託,返回this對象
..........................................................................................................................................
on-finished中依賴的ee-first模塊 作用:通過它我們可以在監聽一系列事件時, 得知哪一個事件最先發生並進行相應的操作
源碼內定義 eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)
res若是websoket, 便改寫eeSocket = first([[socket, 'error', 'close']], onFinish)
..........................................................................................................................................
on-finished模塊 在文中的作用:對請求的處理
koa中handleRequest方法執行了 onFinished(res, onerror); 其中res,onerror便是對應的參數msg和onFinish
createListener方法中,返回的listener雖然是個方法,但也可以在上面繼續追加屬性
..........................................................................................................................................
statuses模塊
定義了一系列狀態碼,返回Boolean
文中function respond() { }中對ctx狀態碼的判斷,寫入res.end()
if (statuses.empty[code]) {
ctx.body = null;
return res.end();
}
..........................................................................................................................................