Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Handle Race Condition in Node Js using Mutex

import { Mutex, MutexInterface } from 'async-mutex';

class PaymentService {
	private locks : Map<string, MutexInterface>;

	constructor() {
		this.locks = new Map();
	}

	public async participateInFreeEvent(user: User, eventId: number): Promise<void> {
        if (!this.locks.has(user.id)) {
          this.locks.set(user.id, new Mutex());
        }
        
        this.locks
            .get(user.id)
            .acquire()
            .then(async (release) => {
                try {
                    const existOrder = await findOrder(eventId, user.id);
                    if (!existOrder) {
                        const order = buildNewOrder(eventId, user.id);
                        createOrder(order.id, eventId, user.id);
                    }
                } catch (error) {
                } finally {
                    release();
                }
            },
        );
    }
}
Source by blog.theodo.com #
 
PREVIOUS NEXT
Tagged: #Handle #Race #Condition #Node #Js #Mutex
ADD COMMENT
Topic
Name
5+9 =