開始學習koa

對koa已經躍躍欲試好久,恰遇koa2最近正式發佈,今天嘗試着倒騰一番。因此本身對koa的學習算是從2.x開始,因爲文檔資源還不徹底,準備踩着前輩們的肩膀,慢慢入坑。javascript

環境的搭建

  • node運行環境,官方文檔標註node v4.0.0及以上版本。java

  • babel,在使用async/await編程時babel是必須的,可是本人未使用async/await,而是使用傳統的promise,因此何嘗試安裝babel。node

常識入門級程序

與大部分程序員同胞同樣樣的習慣,寫一發hello world慰藉本身孤寂的心靈。程序員

const Koa = require('koa');
let app = new Koa();

app.use(ctx => {
    ctx.body = 'hello world';
});

app.listen(3000);

打開瀏覽器,訪問localhost:3000,親切的hello world映入眼簾。web

理解關鍵點

  • (應用上下文)context編程

引用官方解釋:promise

Koa Context 將 node 的 request 和 response 對象封裝在一個單獨的對象裏面,其爲編> 寫 web 應用和 API 提供了不少有用的方法。瀏覽器

許多 context 的訪問器和方法爲了便於訪問和調用,簡單的委託給他們的 ctx.request 和 ctx.response 所對應的等價方法, 好比說 ctx.type 和 ctx.length 代理了 response 對象中對應的方法,ctx.path 和 ctx.method 代理了 request 對象中對應的方法。babel

異步編程實現

koa1提供了generator方式,koa2引入async/await實現,而我獨愛promise處理方式。app

app.use((ctx, next) => {
    const start = new Date();
    return next().then(() => {
        const ms = new Date() - start;
        ctx.body += `1:${ctx.method} ${ctx.url} - ${ms}ms \n`;
    });
});

app.use((ctx, next) => {
    const start = new Date();
    return next().then(() => {
        const ms = new Date() - start;
        ctx.body += `2:${ctx.method} ${ctx.url} - ${ms}ms \n`;
    });
});

app.use((ctx, next) => {
    ctx.body = 'first exec \n';
});

訪問localhost:3000/index,最終結果:

first exec
2:GET /index - 0ms
1:GET /index - 0ms

勉強有點手感,洗簌,睡覺,同志們晚安。

相關文章
相關標籤/搜索