EventQueue
Event queue with support for async-await
reading by a single consumer
Constructor Summary
Public Constructor | ||
public |
Default constructor |
Member Summary
Public Members | ||
public get |
end: * Getter for the end marker. |
Method Summary
Public Methods | ||
public |
Support for |
|
public |
isSignal(signal: *): * Checks whether an object was created by raiseSginal method. |
|
public |
raiseSignal(err: Error) Send a message containing an Error object. |
|
public |
async receive(): * Async method that can be waited on to receive the next message. |
|
public |
send(val: *) Sends a message to a waiting consumer, or stores it in-memory to be delivered later. |
|
public |
shutdown() Closes queue from accepting more messages for delivery |
Public Constructors
Public Members
Public Methods
public isSignal(signal: *): * source
Checks whether an object was created by raiseSginal method.
Params:
Name | Type | Attribute | Description |
signal | * |
Return:
* |
public raiseSignal(err: Error) source
Send a message containing an Error object. Iterator will throw an exception when processing this object
Params:
Name | Type | Attribute | Description |
err | Error | an error to be thrown |
Example:
// Reading from queue using `for await` loop:
let queue = new EventQueue();
setTimeout(() => {
queue.send(0);
queue.send(1);
queue.send(2);
queue.raiseSignal(new Error('Processing failed'));
queue.send(3);
queue.shutdown();
}, 15);
let results = [];
try {
for await (let data of queue) {
results.push(data);
}
}
catch(err) {
// err.message is 'Processing failed'
}
// results contain [0, 1, 2]
// If for some reason one can't use `for await` loop then a similar loop can be implemented using `while`:
let queue = new EventQueue();
setTimeout(() => {
queue.send(0);
queue.send(1);
queue.send(2);
queue.raiseSignal(new Error('Processing failed'));
queue.send(3);
queue.shutdown();
}, 15);
let results = [];
let data;
// while loop checks whether queue was shutdown by comparing returned value
// to a special data member of the queue object. It also checks for signals and throws errors
try {
while ((data = await queue.receive()) !== queue.end) {
if (queue.isSignal(res)) {
throw res.error;
}
results.push(data);
}
}
finally {
}
// results contain [0, 1, 2, 3]
public async receive(): * source
Async method that can be waited on to receive the next message. At most one consumer at a time is expected to be waiting. The method throws an exception after queue was shut down and all pendingmessages were delivered.
Return:
* |
public send(val: *) source
Sends a message to a waiting consumer, or stores it in-memory to be delivered later. Once the queue is shut down, no more messages are accepted for delivery. Pending messages will be delivered to a consumer.
Params:
Name | Type | Attribute | Description |
val | * | value to be delivered |