问题
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