node中间件KOA函数

const Koa = require('koa');

const app = new Koa()

//应用程序对象 中间件

// 发送HTTP KOA 接手HTTP

//中间件(其实就是 函数)

function test(){
console.log("seven month");
}
//当请求发送过来的时候,将函数(中间件)注册到程序上
//前端发送一个http请求 来触发中间件
//koa 中 只会执行第一个中间件

app.use(async(ctx, next)=>{
//ctx 上下文
// next 下一个中间函数
console.log("7")
const a = await next() //调用下一个中间件
// await 可以将promise 中对象 值 直接获取(不通过then)
// await 对表达式求值
//await 阻塞线程(异步) (将异步变为同步)
console.log(a)
// a.then((res)=>{
// console.log(res)
// })
console.log("8")
})
// 洋葱模型(如果有await, 则需要在每个中间件函数前面加async next前面加上 await, ha)

app.use(async(ctx, next) =>{
console.log("9")

const res = await axios.get("http://7yue.pro")
next()

// 对资源的操作 都是异步的 读文件 发送http请求 操作数据库

console.log('10')
return "seven"
})

// 打印结果为7 9 10 8

// 中间件(函数) return 会被强制转换成一个 Promise
app.listen(3000);

 
posted @ 2019-08-28 16:44  淼燚懿  阅读(354)  评论(0编辑  收藏  举报