zoukankan      html  css  js  c++  java
  • 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()执行下一个中间件

     

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

     

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

     

  • 相关阅读:
    学习笔记CSS
    悲剧,当用cywin 写Linux脚本
    .net中控件的命名规则和一些词语的简称(转)(I)
    PyMining开源中文文本数据挖掘平台 Ver 0.2发布
    TCP和UDP的区别(转)
    发一道我今天遇到C面试题(求完美解)
    C#三种定时器的实现转载
    window 拷贝 linux 远程
    datepicker 日月年
    Oracle PL/SQL练习题总目录 hl3292
  • 原文地址:https://www.cnblogs.com/zhanghaoblog/p/11704459.html
Copyright © 2011-2022 走看看