Koa2 middleware插件执行顺序

大家好,我是李俊辉!如果您觉得文章有用,请帮忙点个赞或关注,也为我鼓励一下,坚持写下去!

koaExpress的下一代基于Node.js的web框架,目前是2.11.0版本。
基于ES7 koa2完全使用Promise并配合async来实现异步插件。
下面是一个koa2建立服务器server基础代码:
首先建立一个app.js,输入如下代码:

// 我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');

// 创建一个Koa对象表示web app本身:
const app = new Koa();

// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, Koa2 World!</h1>';
});

// 在端口8080监听:
app.listen(8080);
console.log('http://localhost:8080');

在命令行进入js目录后,输入:node app.js运行server,之后在浏览器输入http://localhost:8080打开页面,可看到页面显示:
Hello, Koa2 World!
这样一个基本的server就完成了。

建立的server服务器每收到一个http请求,koa就会调用通过app.use()注册的async函数,并传入ctx和next参数。我们可以对ctx操作,并设置返回内容。
koa把很多async函数组成一个处理链,每个async函数都可以做一些自己的事情,然后用await next()来调用下一个async函数。我们把每个async函数称为middleware,这些middleware可以组合起来,完成很多有用的功能。

例如,可以用以下3个middleware组成处理链,依次打印日志,记录处理时间,输出HTML:

var Koa = require('koa')
var app = new Koa();
//第1个middleware
app.use(async (ctx, next)=>{
  console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
  await next(); // 调用下一个middleware
});
//第2个middleware
app.use(async (ctx, next)=>{
  const start = new Date().getTime(); // 当前时间
  await next(); // 调用下一个middleware
  const ms = new Date().getTime() - start; // 耗费时间
  console.log(`Time: ${ms} ms`) // 打印耗费时间
});
//第3个middleware
app.use(async (ctx, next)=>{
  await next();
  ctx.response.type = 'text/html';
  ctx.response.body = '<h1>Hello Koa2!!!</h1>';
});

app.listen(3000)
console.log('http://localhost:3000')

插件的输出的结果为:
GET /
Time: 3 ms

middleware的顺序很重要,也就是调用app.use()的顺序决定了middleware的顺序。但是当执行到最后一个await next()后,它继续执行顺序是什么呢?
我们把每一个插件的await next()前后都加入一些log信息看看:

app.use(async (ctx, next)=>{
  console.log(`1-1: ${ctx.request.method} ${ctx.request.url}`);
  await next();
  console.log('1-2')
});

app.use(async (ctx, next)=>{
  const start = new Date().getTime();
  console.log('2-1')
  await next();
  console.log('2-2')
  const ms = new Date().getTime() - start;
  console.log(`Time: ${ms} ms`)
});

app.use(async (ctx, next)=>{
  console.log('3-1')
  await next();
  console.log('3-2')
  ctx.response.type = 'text/html';
  ctx.response.body = '<h1>Hello Koa2!!!</h1>';
});

输出结果为:
1-1: GET /
2-1
3-1
3-2
2-2
Time: 4 ms
1-2

可以看到插件是按照顺序执行的await next()之前的1,2,3,之后按照倒序执行的3,2,1
是不是顺间就明白了koa的middleware的执行顺序了。

如果您觉得文章有用,请帮忙点个赞或关注,也为我鼓励一下,坚持写下去,在此感谢🙏!

转载一定注明出处!
原文地址:https://www.jianshu.com/p/a814b24a5330
2020年2月10日 新冠状病毒期间憋在家

本文参考文章:https://www.liaoxuefeng.com/wiki/1022910821149312/1099752344192192

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

推荐阅读更多精彩内容

  • Koa 学习 历史 Express Express是第一代最流行的web框架,它对Node.js的http进行了封...
    Junting阅读 2,852评论 0 0
  • 参考资料 https://chenshenhai.github.io/koa2-note/note/static/...
    JunChow520阅读 10,518评论 1 8
  • 框架提出的背景 ES6/7带来的变革 自ES6确定和ES7中async/await开始普及,Node的发展变得更加...
    宫若石阅读 8,541评论 1 14
  • 原文链接:http://www.jianshu.com/p/6b816c609669 前传 出于兴趣最近开始研究k...
    悬笔e绝阅读 7,248评论 1 11
  • Q1:什么是中间件 中间件(Middleware),也叫中介层,是提供系统软件和应用软件之间连接的软件,便于软件各...
    BubbleM阅读 576评论 0 0