Skip to content

Instantly share code, notes, and snippets.

@yogurt1 yogurt1/app.js
Last active Jun 14, 2018

Embed
What would you like to do?
Node.js async example
const http = require('http');
const port = process.env.PORT || 3000;
const reqsCount = 50; // Number of requests
const server = http
.createServer((req, res) => {
setTimeout(() => {
res.end(`<h1>EXPENSIVE</h1>`);
}, 1500);
})
.listen(port, () => {
console.log('test app listening on port', port);
test();
});
const doRequest = () =>
new Promise((resolve, reject) =>
http
.get(`http://localhost:${port}`, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => resolve(data));
})
.on('error', reject),
);
const test = async () => {
const timeLabel = `${reqsCount} requests`;
console.time(timeLabel);
const requests = Array.from({length: reqsCount}, doRequest);
const results = await Promise.all(requests);
console.timeEnd(timeLabel);
// console.log('results:', results);
process.exit();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.