KOA 學習(一)


一、安裝KOA

用npm下載KOA 

就會在koa文件夾下生成

二、輸出hello,world

我下載的KOA版本號是2.0.1

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版本的代碼寫的會報錯。

三、生成器函數function*

關鍵詞 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

我分解一下這個程序:

inc 函數定義了一個生成器函數,在每一次 while 循環中,產出 number 變量然后 number 變量加 1inc 函數被指派給了變量 test

inc 函數被迭代了 3 次,第一次的時候,number 變量在函數中被初始化了。然后,這個函數進入到了一個 while 循環,在之后的迭代中這個循環也不會退出。然后 number 0 被產出,所以這個可以用 .value 方法接收。在后來的迭代中這個變量 number 自增了兩次。

我希望這可以幫助理解一點生成器的工作原理。這只是非常復雜的 ES6 中的一小部分。

但是無論如何,讓我們回到 koa。koa 非常簡單,甚至不包含一個路由。你需要在中間件生成器函數中手動做路由匹配:

四、中間件級聯

請求先經過 x-response-time 和 logging 中間件,並記錄中間件執行起始時間。 然后將控制權交給 reponse 中間件。當中間件運行到 yield next 時,函數掛起並將控制前交給下一個中間件。當沒有中間件執行 yield next 時,程序棧會逆序喚起被掛起的中間件來執行接下來的代碼。

ES7(目前是草案,還沒有發布)引入了新的關鍵字asyncawait,可以輕松地把一個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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM