2. Koa中间件与洋葱模型

1. async awaitgit

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

 1. 请求github中的用户接口json

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

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

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)) }) 

 由此咱们能够看出,代码的可读性很差,而咱们这里仅仅是两层嵌套。那咱们该怎么解决这个问题呢?app

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

 

 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写出的代码可读性很是高, 就像咱们写同步请求同样。async

 

2. 洋葱模型fetch

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

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()执行下一个中间件

 

 因此说, 咱们应该能猜到上述代码的结果了:

 

 

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

相关文章
相关标签/搜索