koa1 中间件执行顺序演示

koa的执行顺序第一次看,肯定会混乱,官方文档也只是介绍了yield next的执行顺序,如果我们有自己的异步操作呢?顺序是怎样?让我们简单演示一下

var koa = require('koa');
var app = koa();
var fs = require('co-fs');
// x-response-time
app.use(function *(next){
  console.log('========begin==========');
  // (1) 进入路由
  console.log(1)
  yield next;
  console.log(8);
  console.log('========end==========')
});

// logger
app.use(function *(next){
  console.log(2)
  yield new Promise((resolve) => {
    setTimeout(() => resolve(), 3000);
  });
  console.log(3);
  yield next;
  console.log(5);
  let result = yield fs.readFile('./node_modules/@types/node/index.d.ts', 'utf8');
  console.log(6);
  result = yield new Promise((resolve) => {
    setTimeout(() => resolve(), 3000);
  });
  console.log(7);
});

// response
app.use(function *(){
  console.log(4);
  this.body = 'Hello World';
});

app.listen(10000);

打开chrome浏览器,连续发送请求,观察执行顺序与结果

你可能感兴趣的