qddegtya / a-cheatsheets

:notebook: Awesome cheatsheets
Creative Commons Zero v1.0 Universal
0 stars 1 forks source link

理解 koa 中间件核心 #11

Open qddegtya opened 8 years ago

qddegtya commented 8 years ago
#!/usr/bin/env node

// 中间件 a
function* a(next) {
  yield 1;

  // 执行下一个中间件
  yield* next;

  yield '继续执行A中间件';
}

// 中间件 b
function* b(next) {
  yield 2;
  yield 3;
}

var next = function* (){};
var i = [a, b].length;

// 通过next首尾相连
while(i--) {
  next = [a, b][i].call(null, next);
}

// 包裹第一个middleware
function* start(ne) {
  yield* ne;
}

// 输出
console.log(start(next).next());
console.log(start(next).next());
console.log(start(next).next());
console.log(start(next).next());

结果:

➜  a-lab ./a
{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: '继续执行A中间件', done: false }