Skip to content

Instantly share code, notes, and snippets.

@nebarf
Created June 4, 2021 09:54
Show Gist options
  • Save nebarf/6a02686a7fa57f0460a7d0d4e3897685 to your computer and use it in GitHub Desktop.
Save nebarf/6a02686a7fa57f0460a7d0d4e3897685 to your computer and use it in GitHub Desktop.
const http = require('http');
class Queue {
constructor(executor) {
this._queue = [];
this._commandQueue = [];
const enqueue = (item) => {
this._queue.push(item);
this._commandQueue.forEach(command => command());
this._commandQueue = [];
};
executor(enqueue);
}
dequeue() {
if (this._queue.length === 0) {
return new Promise((resolve, reject) => {
const command = () => this.dequeue().then(resolve, reject);
process.nextTick(() => this._commandQueue.push(command));
});
}
return new Promise((resolve, reject) => {
try {
const item = this._queue.shift();
resolve(item);
} catch (err) {
reject(err);
}
});
}
}
const messagesQueue = new Queue((enqueue) => {
http
.createServer((req, res) => {
let data = '';
req.on('data', chunk => {
data += chunk;
});
req.on('end', () => {
enqueue(data);
res.end();
});
})
.listen(8080, async () => {
console.log('Server listening on http://localhost:8080');
console.log('Waiting for messages to be enqueued...');
while (true) {
const msg = await messagesQueue.dequeue();
console.log(`Dequeued message "${msg}"`);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment