1.await关键字只能在async函数中使用
2.await 相当于then,获取promise—resolve的结果
<script>
/* await
1.相当于执行了promise的then函数
2.await后面不一定更promise
3.await阻塞了代码执行流程,会优先执行后面的同步任务
*/
async function show(){
console.log("start");
await mid();
// var res =await mid();
// console.log(res);
console.log("end");
}
async function mid(){
console.log("mid");
return 1;
}
show();
console.log("a1");
</script>
<script>
/* await会阻塞函数的执行,
会优先执行await后面同步的代码,
异步代码等待同步代码执行完毕后再去执行 */
async function a1(){
console.log("a1");
await a2();
console.log("end");
}
async function a2(){
console.log("a2");
}
a1();
console.log("a3");
Promise.resolve().then(()=>
{console.log("a4");}
)
</script>
标准洋葱模型
const koa =require("koa");
const { nextTick } = require("process");
const app=new koa();
/* app.use(fn) fn--中间件
中间件:路由匹配之前和路由完成之后要进行的一些操作就加中间件
*/
/*
中间件函数有两个参数:ctx next
next指的是下一个中间件
*/
app.use(async (ctx,next)=>{
console.log("fn1")
var res = await next();
console.log(res);
console.log("4");
})
app.use(async (ctx,next)=>{
console.log("fn2")
await next();
console.log("3");
return "second"
})
app.listen(4000);
/*
fn1
fn2
3
second
4
*/
使用中间件执行过滤
ctx.path —-可以获取路由的路径
const koa =require("koa");
const app=new koa();
const router =require("koa-router")();
/* 如果没有next,下一个中间函数不会执行 */
/* 没读取一个路由页面,都会经过这个中间件函数 */
app.use(async(ctx,next)=>{
console.log("login");
console.log(ctx.path); ---可以获取路由的路径
if(ctx.path=="/user"){
ctx.body="不可查看"
}else{
await next();
}
})
router.get("/",async ctx=>{
ctx.body="首页"
})
router.get("/user",async ctx=>{
ctx.body="核心代码"
})
router.get("/my",async ctx=>{
ctx.body="my"
})
app.use(router.routes())
app.listen(4000);