koa await next()

当一个中间件调用 next() 则该函数暂停并将控制传递给定义的下一个中间件。当在下游没有更多的中间件执行后,堆栈将展开并且每个中间件恢复执行其上游行为。

// require("babel-register");
const http = require('http');
const https = require('https');
const Koa = require('koa');
const nexttest = require("./nexttest");
const app = new Koa();


// x-response-time
app.use(async (ctx, next) => {
  const start = Date.now();
  console.log('------1---------');
  await next();
  console.log('------2---------');

  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger
app.use(async (ctx, next) => {
  const start = Date.now();
  console.log('------3--------');

  await next();
  console.log('------4---------');

  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

app.use(async (ctx, next) => {
  console.log('------5--------');

  await next();
  console.log('------6---------');

});

// response
app.use(async ctx => {
  console.log('------7---------');

  ctx.body = ctx.response.status;
});

http.createServer(app.callback()).listen(3000);
// https.createServer(app.callback()).listen(3000);

输出:

------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 2
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET / - 0
------2---------
------1---------
------3--------
------5--------
------7---------
------6---------
------4---------
GET /favicon.ico - 0
------2---------
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,107评论 19 139
  • github地址,欢迎大家提交更新。 express() express()用来创建一个Express的程序。ex...
    Programmer客栈阅读 7,563评论 0 1
  • Koa 学习 历史 Express Express是第一代最流行的web框架,它对Node.js的http进行了封...
    Junting阅读 7,843评论 0 0
  • Koa 必须使用 7.6 以上的版本。如果你的版本低于这个要求,就要先升级 Node。 基本用法 Koa 提供一个...
    Gukson666阅读 7,170评论 0 1
  • 楔子 七月的江南,闷得人透不过气,合欢坐在空调房里,翘着二郎腿跟学姐侃大山。顾成译的电话就是在这个时候打来的。 看...
    柚子小七_9abe阅读 1,810评论 0 0

友情链接更多精彩内容