koa中同步与异步的写法

koa中间件洋葱圈模型,同步的写法

//node server.js
//中间件机制
const Koa = require('koa')
const app = new Koa()
// app.use(async(ctx,next)=>{
//     ctx.body = 'hello imooc'
// })
// 运行结果
// 135642
app.use(async(ctx,next)=>{
    ctx.body = '1'
    //下一个中间件
    next()
    ctx.body = ctx.body + '2'
})
app.use(async(ctx,next)=>{
    ctx.body+= '3'
    //下一个中间件
    next()
    ctx.body = ctx.body + '4'
})
app.use(async(ctx,next)=>{
    ctx.body += '5'
    //下一个中间件
    next()
    ctx.body = ctx.body + '6'
})
//启动应用
app.listen('9002')

koa中间件洋葱圈模型,异步的写法

//135642
const Koa = require('koa')
const app = new Koa()
// app.use(async(ctx,next)=>{
//     ctx.body = 'hello imooc'
// })
// 运行结果
// 135642
function delay(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve()
        },1000)
    })
}
app.use(async(ctx,next)=>{
    ctx.body = '1'
    //下一个中间件
    // setTimeout(()=>{
    //     next()
    // },2000)
  
    await next()
    ctx.body = ctx.body + '2'
})
app.use(async(ctx,next)=>{
    ctx.body+= '3'
    //下一个中间件
    await next()
    ctx.body = ctx.body + '4'
})
app.use(async(ctx,next)=>{
    ctx.body += '5'
    await delay()
    //下一个中间件
    await next()
    ctx.body = ctx.body + '6'
})
//启动应用
app.listen('3000')

猜你喜欢

转载自www.cnblogs.com/smart-girl/p/11270786.html