koa中同步與異步的寫法

koa中間件洋蔥圈模型,同步的寫法node

//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中間件洋蔥圈模型,異步的寫法app

//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')
相關文章
相關標籤/搜索