• express与koa的一点对比


    express: 

    var express=require('express');
    var app=express();
    
    // 异常处理
    app.use((req,res,next)=>{
        try{
            next();
        }catch(ex){
            res.send(ex.message);
        }
    })
    
    
    app.use((req,res,next)=>{
        console.log(1);     // 1
        next();             // 2
        console.log(2);     // 5  执行时机不确定,与是否异步有关
    });
    
    app.use((req,res,next)=>{
        console.log(3);     // 3
        new Promise(resolve=>{  // 4
            setTimeout(resolve,300);
        }).then(()=>{
            next();         // 6
            console.log(4); // 8
        })
    });
    
    app.use((req,res)=>{
        // 7
        try{
            res.send('Hello World');
            throw new Error('hehe');
        }catch(ex){
            // 异常处理
        }
    });
    
    app.listen(3000);

    koa:

    const Koa=require('koa');
    const app=new Koa();
    
    // 异常处理
    app.use(require('./koa-error'));
    
    process.on('unhandledRejection',err=>{
        console.error(`unhandledRejection: ${err.message}, stack: ${err.stack}`);
    });
    
    process.on('uncaughtException',err=>{
        console.error(`uncaughtException: ${err.message}, stack: ${err.stack}`);
    })
    
    app.use(async (ctx,next)=>{
        console.log(1);     // 1
        next();             // 2  -----以next为分界线,会先执行next之前的方法,再执行next之后的方法
        console.log(2);     // 8  
    });
    
    app.use(async (ctx,next)=>{
        console.log(3);     // 3
        await new Promise(resolve=>{
            setTimeout(resolve,300);
        });     // 4
    
        await next();       // 5
        console.log(4);     // 7
    });
    
    app.use(async (ctx,next)=>{
        ctx.body='hello world';
    });
    
    app.listen(3000);
  • 相关阅读:
    K8s中Secrets
    记一次kubernetes配置secret拉取私仓镜像错误
    K8S中ConfigMap
    阿里云RDSforMySQL如何定位本地IP
    Python3运算符
    nyoj 67-三角形面积 (海伦公式, 叉积)
    nyoj 66-分数拆分 (Java,暴力)
    nyoj 65-另一种阶乘问题 (Java 高精度)
    nyoj 64-鸡兔同笼 (解二元一次方程)
    nyoj 63-小猴子下落 (模拟)
  • 原文地址:https://www.cnblogs.com/jingouli/p/11630580.html
Copyright © 2020-2023  润新知