Async/Await degrades server performance

拟墨画扇 提交于 2019-12-25 01:18:58

问题


I'm using the following code to write a HTTP server to check if using async/await can impact the performance

const http = require('http')

const server = http.createServer(reqResHandler);

server.listen(3000, err => {
  if (err) throw err
  console.log('Server listening on: http://localost:3000')
})

Without Promise

const reqResHandler = (req, res) => {
    req.body = [];
    req.on('data', (chunk)=>req.body.push(chunk));
    req.on('end', ()=>{
      req.body = Buffer.concat(req.body);
      res.setHeader("content-length", req.body.length);
      res.end(req.body);
    });

};

With Promise

async function getBody(req){
    var end = new Promise(function(resolve, reject) {
      req.on('data', (chunk)=>req.body.push(chunk));
      req.on('end', ()=>{req.body = Buffer.concat(req.body); resolve(req.body)});
      req.on('error', reject); // or something like that
  });

  await end;

  return req.body;
}


const reqResHandler = async (req, res) => {
    req.body = [];
    var data = await getBody(req);
    res.setHeader("content-length", data.length);
    res.end(data);
};

When I use the code without promise it gives throughput up to 30-31k requests per second. But if I use code with promise then it gives performance up to 27-27.5k rps max.

Am I using the async await incorrectly?


回答1:


You can do the async like this:

async function getBody(req){
return new Promise(function(resolve, reject) {
  req.on('data', (chunk)=>req.body.push(chunk));
  req.on('end', ()=>{req.body = Buffer.concat(req.body); resolve(req.body)});
  req.on('error', reject); // or something like that
});
}


 const reqResHandler = async (req, res) => {
req.body = [];
let data = (await getBody(req)).body;
res.setHeader("content-length", data.length);
res.end(data);

};



来源:https://stackoverflow.com/questions/49537568/async-await-degrades-server-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!