對于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')
})
//輸出結(jié)果為
// Here is the first one
// Here is the second one
由于當(dāng)時理解洋蔥模型時候,不夠理解透徹,當(dāng)時認(rèn)為只是簡單的layer through layer,每一個layer只是單單為一個二維平面,但是實(shí)際上,Koa的洋蔥模型,每一層layer相當(dāng)于一個球面,當(dāng)貫穿整個模型時,實(shí)際上每一個球面(sophere)會穿透兩次,在首先理解這個點(diǎn)時,先熟悉一下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ù)
// 輸出結(jié)果為
//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
//典型的洋蔥結(jié)構(gòu)
對于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中間件的核心思想