首页 > 其他 > 详细

express与koa的一点对比

时间:2019-10-07 16:49:23      阅读:110      评论:0      收藏:0      [点我收藏+]

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

 

express与koa的一点对比

原文:https://www.cnblogs.com/jingouli/p/11630580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!