入门

  1. const Koa = require('koa')
  2. const app = new Koa()
  3. function test() {
  4. console.log('hello 7yue')
  5. }
  6. app.use(test)
  7. app.listen(3000)

中间件的理解

app.use为中间件,只有在进行请求时才会被调用

koa如何传递参数以及链式调用的

通过ctx,上下文 以及next执行,也就是下个函数

  1. const Koa = require('koa')
  2. const app = new Koa()
  3. function test() {
  4. console.log('hello 7yue')
  5. }
  6. function test1() {
  7. console.log('hello 8yue')
  8. }
  9. app.use((ctx,next)=>{
  10. test()
  11. next()
  12. })
  13. app.use(test1)
  14. app.listen(3000)

洋葱模型的执行特点

image.png

比如下面函数的打印结果: 1 3 4 2

  1. const Koa = require('koa')
  2. const app = new Koa()
  3. app.use((ctx,next)=>{
  4. console.log(1)
  5. next()
  6. console.log(2)
  7. })
  8. app.use(async (ctx,next)=>{
  9. console.log(1)
  10. await next()
  11. console.log(2)
  12. })
  13. app.use((ctx,next)=>{
  14. console.log(3)
  15. next()
  16. console.log(4)
  17. })
  18. app.listen(3000)

那么如何保证程序的确定能按照洋葱模型执行呢?加async await 即可。

为什么要保证洋葱模型

要知道后面函数都执行完成,或者要知道其执行结果,比如计时

不同中间件如何传值 ?利用ctx

  1. app.use(async(ctx,next)=>{
  2. console.log(1)
  3. await next()
  4. console.log(ctx.str)
  5. console.log(2)
  6. })
  7. app.use((ctx,next)=>{
  8. console.log(3)
  9. const str = 'yyue'
  10. ctx.str = str
  11. next()
  12. console.log(4)
  13. })

await 意义

1 等待求值
2 阻塞线程,阻塞代码一般情况下是不方便验证,但异步逻辑是方便验证的,常见的异步操作有网络请求,读取文件,操作数据库。

小常识

验证执行时间,在程序执行前后桌架系统时间,做差

async的函数会被包装为promise函数