2. Koa中间件与洋葱模型

时间:2019-10-19
本文章向大家介绍2. Koa中间件与洋葱模型,主要包括2. Koa中间件与洋葱模型使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. async await

 为了更好的理解aysnc、await, 我们先请求两个接口

 1. 请求github中的用户接口

//请求github用户接口
fetch("//api.github.com/users")
    .then(res => res.json())
    .then(json => console.log(json))

 2. 请求github中的用户接口后, 请求特定用户接口  

fetch("//api.github.com/users")
    .then(res => res.json())
    .then(json => {
      console.log(json)
      fetch("//api.github.com/users/CQzhanghao")
      .then(res => res.json())
      .then(json => console.log(json))
    })
    

 由此我们可以看出,代码的可读性不好,而我们这里仅仅是两层嵌套。那我们该怎么解决这个问题呢?

 我们可以尝试使用下ES7的新语法 async、await, 号称是解决异步请求的最终方案

 3. 用async、await重写上面两段请求方法

  

//请求github用户接口, 再请求特定用户
async () => {
  const res = await fetch("//api.github.com/users")
  const json = await res.json()
  console.log(json)
  const res2 = await fetch("//api.github.com/users/CQzhanghao")
  const json2 = await res.json()
  console.log(json2)
}

  对比一下, 可以明显看出用async、await写出的代码可读性非常高, 就像我们写同步请求一样。

2. 洋葱模型

 洋葱模型是Koa中的一个重要概念, 我们通过一个例子来看看它是什么

const Koa = require('koa')
const app = new Koa()

//第一个中间件
app.use(async (ctx, next) => {
  console.log("第一个中间件 next执行前")
  await next()
  console.log("第一个中间件 next执行后")
})

//第二个中间件
app.use(async (ctx, next) => {
  console.log('第二个中间件 next执行前')
  await next()
  console.log('第二个中间件 next执行后')
})

//第三个中间件
app.use(async (ctx, next) => {
  console.log('第三个中间件 next执行前')
  await next()
  console.log('第三个中间件 next执行后')
})

app.listen(3002)

 一个中间件有两个参数, 第一个是ctx。ctx是由koa传入的封装了request和response的变量,我们可以通过它访问request和response.

 另一个是next, next是指这个中间件下面的那个中间件,koa里面的所有功能都是通过中间件来完成的

 在上面的代码中,我们可以使用用await next()执行下一个中间件

 

 所以说, 我们应该能猜到上述代码的结果了:

 

  可以看出, 这执行过程就像一个洋葱, 从外到里,再由里到外。

 

原文地址:https://www.cnblogs.com/zhanghaoblog/p/11704459.html