Hard
Fixing Race Conditions and Error Handling in Async Notification Queue System
You're building a notification system for a chat application that needs to handle messages from multiple channels (email, SMS, push notifications). The system needs to process these notifications in order of priority but also handle failures gracefully. What's wrong with this implementation?
1class NotificationSystem {2 constructor() {3 this.queue = [];4 this.processing = false;5 }67 async addNotification(notification) {8 this.queue.push({9 ...notification,10 timestamp: Date.now(),11 retries: 012 });1314 if (!this.processing) {15 await this.processQueue();16 }17 }1819 async processQueue() {20 this.processing = true;2122 while (this.queue.length > 0) {23 const notification = this.queue.shift();24 try {25 await this.sendNotification(notification);26 } catch (error) {27 if (notification.retries < 3) {28 notification.retries++;29 this.queue.push(notification);30 }31 }32 }3334 this.processing = false;35 }3637 async sendNotification(notification) {38 // Simulated API call39 return fetch(`/api/${notification.type}`, {40 method: 'POST',41 body: JSON.stringify(notification)42 });43 }44}