Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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