1.await关键字只能在async函数中使用
2.await 相当于then,获取promise—resolve的结果
image.png

  1. <script>
  2. /* await
  3. 1.相当于执行了promise的then函数
  4. 2.await后面不一定更promise
  5. 3.await阻塞了代码执行流程,会优先执行后面的同步任务
  6. */
  7. async function show(){
  8. console.log("start");
  9. await mid();
  10. // var res =await mid();
  11. // console.log(res);
  12. console.log("end");
  13. }
  14. async function mid(){
  15. console.log("mid");
  16. return 1;
  17. }
  18. show();
  19. console.log("a1");
  20. </script>

image.png

  1. <script>
  2. /* await会阻塞函数的执行,
  3. 会优先执行await后面同步的代码,
  4. 异步代码等待同步代码执行完毕后再去执行 */
  5. async function a1(){
  6. console.log("a1");
  7. await a2();
  8. console.log("end");
  9. }
  10. async function a2(){
  11. console.log("a2");
  12. }
  13. a1();
  14. console.log("a3");
  15. Promise.resolve().then(()=>
  16. {console.log("a4");}
  17. )
  18. </script>

image.png


标准洋葱模型

  1. const koa =require("koa");
  2. const { nextTick } = require("process");
  3. const app=new koa();
  4. /* app.use(fn) fn--中间件
  5. 中间件:路由匹配之前和路由完成之后要进行的一些操作就加中间件
  6. */
  7. /*
  8. 中间件函数有两个参数:ctx next
  9. next指的是下一个中间件
  10. */
  11. app.use(async (ctx,next)=>{
  12. console.log("fn1")
  13. var res = await next();
  14. console.log(res);
  15. console.log("4");
  16. })
  17. app.use(async (ctx,next)=>{
  18. console.log("fn2")
  19. await next();
  20. console.log("3");
  21. return "second"
  22. })
  23. app.listen(4000);
  24. /*
  25. fn1
  26. fn2
  27. 3
  28. second
  29. 4
  30. */

使用中间件执行过滤

ctx.path —-可以获取路由的路径

  1. const koa =require("koa");
  2. const app=new koa();
  3. const router =require("koa-router")();
  4. /* 如果没有next,下一个中间函数不会执行 */
  5. /* 没读取一个路由页面,都会经过这个中间件函数 */
  6. app.use(async(ctx,next)=>{
  7. console.log("login");
  8. console.log(ctx.path); ---可以获取路由的路径
  9. if(ctx.path=="/user"){
  10. ctx.body="不可查看"
  11. }else{
  12. await next();
  13. }
  14. })
  15. router.get("/",async ctx=>{
  16. ctx.body="首页"
  17. })
  18. router.get("/user",async ctx=>{
  19. ctx.body="核心代码"
  20. })
  21. router.get("/my",async ctx=>{
  22. ctx.body="my"
  23. })
  24. app.use(router.routes())
  25. app.listen(4000);