Executing Express res.render in a async manner

2019-06-23 21:53发布

I have a nodejs application where res.render method of express is taking about 400 ms in a blocking way. How do I handle this to execute in a non blocking way? My apache benchmark takes 12 seconds for executing around 30 concurrent requests. How do I implement this in a better manner?

var start = +new Date;
//fetch data from redis
console.log('time taken to fetch data from redis ' + (+new Date - start)); //30 ms
res.render('some_jade_view', params);
console.log('time taken to render data ' + (+new Date - start)); //530 ms

I tried process.nextTick but it did not help much, ab results are the same.

1条回答
混吃等死
2楼-- · 2019-06-23 22:50

I think you should really take a look into https://github.com/caolan/async.

Directly from Async's repo:

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. (...)

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

Cheers.

Edit: I'm not sure if rendering your view in an asynchronous manner would really help you reduce your times. You may want to implement a stream on the client side that fetches and templates the data as it is coming along. You could use a front end framework like Angular for that, or do it manually.

查看更多
登录 后发表回答