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);

 

posted @ 2019-10-07 16:02  金钩梨  阅读(328)  评论(0)    收藏  举报