When handling concurrent operations in asynchronous environments, avoid mutating shared state that could lead to race conditions. Instead, create operation-specific state or use immutable patterns to ensure each request path has isolated context.
Problem example:
// PROBLEMATIC: Mutating shared socket instance can cause race conditions
Object.assign(socket, {
getPattern: () => this.reflectCallbackPattern(currentCallback),
});
If multiple messages arrive nearly simultaneously, they could overwrite each other’s metadata before processing completes.
Better approach:
// Create request-specific context instead of modifying shared objects
class WsArgumentHost {
constructor(private client: any, private callback: MessageHandler) {}
getClient() {
return this.client;
}
getPattern() {
return this.reflectCallbackPattern(this.callback);
}
}
Other best practices:
Enter the URL of a public GitHub repository