美文网首页编程go之Nodejs
Node.js Koa 之Async中间件

Node.js Koa 之Async中间件

作者: 编程go | 来源:发表于2017-03-26 16:46 被阅读1320次

A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request. Koa is similar to many other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on - however a key design decision was made to provide high level "sugar" at the otherwise low-level middleware layer. This improves interoperability, robustness, and makes writing middleware much more enjoyable.

Koa 在2017-02-25 发布了2.0 版本,详情请参照git hub 上history.md

1.0 与2.0 版本关于中间件的异同

1.0 版本是通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升错误处理的效率。
2.0版本Koa放弃了generator,采用Async 函数实现组件数组瀑布流式(Cascading)的开发模式。

先来看看Koa 2.0 版本Hello word的demo,

const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

Koa中间件的方式

Common function
/* Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
 next is a function that is invoked to execute the downstream middleware. 
It returns a Promise with a then function for running code after completion. */

app.use((ctx, next) => {
  const start = new Date();
  return next().then(() => {
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
  });
});
Async function
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

async与common function 的区别主要在于语法糖面前是否存在async,如果需要同步的执行中间件或是函数,只需要在中间件或函数前加关键字await。

// 同步执行中间件
app.use(async (ctx, next) => { await next(); });

Koa Cascading 中间件值的传递

Middleware1 中间件中的函数next()返回的是一个promise 对像

const Koa = require('koa');
const app = new Koa();
//Middleware 1
app.use(async function (ctx, next) {
    console.log("1.1")
    await next().then(function (data) {
        console.log(data)               // "Spursyy"
    }).catch(function (err) {
        console.log(err)
    });
    console.log("1.2")

})
//Middleware 2
app.use(async function (ctx, next) {
   return new Promise (function (resolve, reject) {
       resolve("Spursyy")
   })
})

app.listen(3000);
console.log("port 3000 was start!")

相关文章

  • 知识点总结

    Koa2中间件 koa(面向node.js的表达式HTTP中间件框架)、koa-router(路由中间件)、koa...

  • Node.js Koa 之Async中间件

    A Koa application is an object containing an array of mid...

  • Node.js 常用中间件

    Node.js 常用中间件 async jsonwebtoken bluebird crypto mongoose...

  • koa2学习笔记

    快速开始 安装 node.js 版本:v7.6 以上 npm i koa -S 运行 async / await ...

  • Koa常用中间件(持续更新)

    首先介绍中间件是Koa中一个非常重要的概念。Koa应用程序就是包含一组中间件函数的对象,而且有了async/awa...

  • KOA2-快速上手

    KOA2与KOA1相比最大的特点是采用了async/await,但是Node.js环境需要7.6.0以上。如果不想...

  • nodejs使用async/await同步操作mysql

    注: 教程基于koa2 node.js版本需要>=7.6, 当然同样适用于express,因为async/awai...

  • Koa 中间件的执行顺序

    一、概念 Koa 应用程序是一个包含一组中间件函数的对象。 1. async和await在koa中使用关键词 as...

  • koa系列(三)

    文章内容:koa 中间件 以及 koa 中间件的执行流程。 一、什么是 Koa 的中间件 中间件就是匹配路由之前或...

  • NodeJs框架 Koa

    目录 一、简介 二、 Koa之hello world 三、服务器自动重新部署 四、Koa中间件 五、Koa路由配置...

网友评论

    本文标题:Node.js Koa 之Async中间件

    本文链接:https://www.haomeiwen.com/subject/dilkottx.html