Q14: Implement an Async Publish-Subscribe Bus
Create an event bus that supports asynchronous subscriber callbacks, returning a promise from publish() that resolves once all subscriber callbacks settle.
Async Event Bus
class AsyncEventBus {
constructor() {
this.subscribers = new Map();
}
subscribe(event, callback) {
if (!this.subscribers.has(event)) this.subscribers.set(event, new Set());
this.subscribers.get(event).add(callback);
return () => this.subscribers.get(event).delete(callback);
}
async publish(event, data) {
if (!this.subscribers.has(event)) return [];
const callbacks = Array.from(this.subscribers.get(event));
const promises = callbacks.map(cb => Promise.resolve().then(() => cb(data)));
return Promise.all(promises);
}
}💡 Publishing wraps each callback in a Promise, allowing Promise.all to await all subscriber operations concurrently.
Key Takeaways
- Returns an un-subscribe teardown closure upon registration.
- Uses Promise.all to execute and await subscriber handlers concurrently during publication.
Knowledge Check
What is the return result of publishing an event in the AsyncEventBus above?