node - koa中间件

不想你离开。 提交于 2020-02-10 17:42:47

koa中的中间件分析:

用输出顺序模拟了了koa的洋葱模型,借着输出结果,分析下输出下边结果的原因:

看到我使用了async和await,会明白中间件参数函数是异步函数,因为里边的next( ) 是异步的 ( next()相当于下一个中间件 ),输出2的时机是:必须等到下一个中间件执行完毕后,才能输出2。

const Koa = require('koa')
const app = new Koa()
// 洋葱模型: 执行顺序是 1 3 4 2
app.use( async (ctx, next) => {
    console.log('1')
    await next()
    console.log('2')
})
app.use( async (ctx, next) => {
    console.log('3')
    await next()
    console.log('4')
})
app.listen(3000)

其实,next返回的是一个Promise对象,之所以里边为undefined,因为下一个中间件没有返回值。

// 洋葱模型: 执行顺序是 1 3 4 Promise{undefined} 2
app.use((ctx, next) => {
    console.log('1')
    const nextPromise = next()
    console.log(nextPromise)
    console.log('2')
})
app.use( async (ctx, next) => {
    console.log('3')
    // await next()
    console.log('4')
})

 

改写

所以上边使用的sync 和await写法,可以改成如下:

// 洋葱模型: 执行顺序是 1 3 4 Promise{undefined} 2
app.use((ctx, next) => {
    console.log('1')
    const nextPromise = next()
    nextPromise.then((res) => {
        console.log('res', res)
        console.log('2')
    })
})
app.use( async (ctx, next) => {
    console.log('3')
    // await next()
    console.log('4')
})

 

tips:

1、如果上边代码不加async,next() 的返回结果仍然是一个Promise对象,原因koa框架内部已经处理。

2、为什么每个next() 前需要加上await:

保证代码的执行顺序,也就是"洋葱模型的执行顺序"

// '1' -> '3' -> '5' -> '6' -> '4' -> '2'
app.use(async (ctx, next) => {
    console.log('1')
    await next()
    console.log('2')
})
app.use( async (ctx, next) => {
    console.log('3')
    await next()
    console.log('4')
})
app.use(async (ctx, next) => {
    console.log('5')
    await next()
    console.log('6')
})

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!