Koa中间件思想
2018-07-19 本文已影响142人
losspm
对于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* 代表会执行后面的函数
// 输出结果为
//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');
});
//执行熟悉如下
f1: pre next
f2: pre next
f3: pre next
f3: post next
f2: post next
f1: post next
每个中间件会执行两次,这就是Koa中间件的核心思想