Koa中間件思想

對于node.js而言,目前接觸的比較多的就是Express框架,對于Express框架的中間件理解就是,一層一層逐級往下,類似流水線上的每一個工序,如下

const express = require('express');
const app = new express();

app.use(function(){
  console.log('Here is the first one';)
})

app.use(function(){
  console.log('Here is the second one')
})

//輸出結果為
// Here is the first one
// Here is the second one

由于當時理解洋蔥模型時候,不夠理解透徹,當時認為只是簡單的layer through layer,每一個layer只是單單為一個二維平面,但是實際上,Koa的洋蔥模型,每一層layer相當于一個球面,當貫穿整個模型時,實際上每一個球面(sophere)會穿透兩次,在首先理解這個點時,先熟悉一下ES6的 yield 語法

class Test{
  constructor(){
    this.state = this.fn1();
    this.state.next();
    this.state.next();
  }
  *fn1(){
    console.log('This is fn1, phase 1');
    yield* this.fn2();
    console.log('This is fn1, phase 2');
  }
  *fn2(){
    console.log('This is fn2, phase 1');
    yield* this.fn3();
    console.log('This is fn2, phase 2');
  }
  *fn3(){
    console.log('This is fn3, phase 1');
    console.log('This is fn3, phase 2');
  }
}

const test = new Test();

// 此時的yield* 代表會執(zhí)行后面的函數(shù)
// 輸出結果為
//This is fn1, phase 1
//This is fn2, phase 1
//This is fn3, phase 1
//This is fn3, phase 2
//This is fn2, phase 2
//This is fn1, phase 2
//典型的洋蔥結構

對于Koa

var koa = require('koa');
var app = koa();

app.use(function* f1(next) {
    console.log('f1: pre next');
    yield next;
    console.log('f1: post next');
});

app.use(function* f2(next) {
    console.log('  f2: pre next');
    yield next;
    console.log('  f2: post next');
});

app.use(function* f3(next) {
    console.log('    f3: pre next');
    this.body = 'hello world';
    console.log('    f3: post next');
});

//執(zhí)行熟悉如下
f1: pre next
  f2: pre next
    f3: pre next
    f3: post next
  f2: post next
f1: post next

每個中間件會執(zhí)行兩次,這就是Koa中間件的核心思想

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 前言 Koa 是運行在 Node.js 中的 web 服務框架,小而美。 Koa2 是 Koa 框架的最新版本,K...
    let_Scott閱讀 5,892評論 2 28
  • 看到標題,也許您會覺得奇怪,redux跟Koa以及Express并不是同一類別的框架,干嘛要拿來做類比。盡管,例如...
    Perkin_閱讀 1,797評論 0 4
  • 孤鷹不褪羽,哪能得高飛,蛟龍不脫皮,何以上青天。 老鷹是世界上,壽命最長的鳥類,它的年齡可達七十歲,為什么鷹會...
    演講教練鄭俊杰閱讀 1,306評論 0 4
  • 吉晚晚是個神經(jīng)大條、十分迷糊的姑娘,她第一次見到向左是在一堂公開課上。當時向左穿著一件潔白的襯衫,身姿挺拔的站在講...
    兮云閱讀 368評論 0 3
  • 人工智能與翻譯(一) 當前人工智能快速發(fā)展,在翻譯上也逐步得到應用,但人工智能的譯文要達原意,還有較長的路要走。 ...
    西雨流星河閱讀 1,981評論 0 0

友情鏈接更多精彩內(nèi)容