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* 代表会执行后面的函数
// 输出结果为
//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中间件的核心思想

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 Koa 是运行在 Node.js 中的 web 服务框架,小而美。 Koa2 是 Koa 框架的最新版本,K...
    let_Scott阅读 5,804评论 2 28
  • 看到标题,也许您会觉得奇怪,redux跟Koa以及Express并不是同一类别的框架,干嘛要拿来做类比。尽管,例如...
    Perkin_阅读 1,745评论 0 4
  • 孤鹰不褪羽,哪能得高飞,蛟龙不脱皮,何以上青天。 老鹰是世界上,寿命最长的鸟类,它的年龄可达七十岁,为什么鹰会...
    演讲教练郑俊杰阅读 1,241评论 0 4
  • 吉晚晚是个神经大条、十分迷糊的姑娘,她第一次见到向左是在一堂公开课上。当时向左穿着一件洁白的衬衫,身姿挺拔的站在讲...
    兮云阅读 337评论 0 3
  • 人工智能与翻译(一) 当前人工智能快速发展,在翻译上也逐步得到应用,但人工智能的译文要达原意,还有较长的路要走。 ...
    西雨流星河阅读 1,628评论 0 0