Skip to content

Instantly share code, notes, and snippets.

@s-steephan
Last active October 10, 2023 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-steephan/d6cdff2168601491e5472e62463615e1 to your computer and use it in GitHub Desktop.
Save s-steephan/d6cdff2168601491e5472e62463615e1 to your computer and use it in GitHub Desktop.
const express = require('express');
const { AsyncLocalStorage } = require('async_hooks');
const http = require('http');
const asyncLocalStorage = new AsyncLocalStorage();
const app = express();
app.use((req, res, next) => {
asyncLocalStorage.run({
seqId: req.query.seqId // Set here
}, next);
});
// Route handler to count numbers up to 5
app.get('/count-to-five', (req, res) => {
let count = 1;
const timer = setInterval(() => {
const seqId = asyncLocalStorage.getStore().seqId; // Get here
console.log(`${seqId}: count: ${count}`);
if (count === 5) {
clearInterval(timer);
console.log(`<--- ${seqId}: finished --->`);
res.send('Counted to 5!');
}
count++;
}, 1000);
});
app.listen(8080, () => {
console.log('Server is running on port 8080');
// Test call
http.get('http://localhost:8080/count-to-five?seqId=FirstInstance');
http.get('http://localhost:8080/count-to-five?seqId=SecondInstance');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment