zoukankan      html  css  js  c++  java
  • 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')
    
  • 相关阅读:
    Linux 命令大全
    MySQL 存储 utf8mb4
    PHP房贷计算器代码,等额本息,等额本金
    laravel 原生 sql
    include_once 问题
    laravel count distinct
    微信小程序显示cms里的html文章
    PHP文件上传
    Ajax做无刷新分页
    PHP封装返回Ajax字符串和JSON数组
  • 原文地址:https://www.cnblogs.com/smart-girl/p/11270786.html
Copyright © 2011-2022 走看看