JavaScript is in no way immune from race conditions.
With JavaScript's most common use case being web application (both front-end and back-end), input and output are therefore not synchronous. Hence the need devise synchronization paradigmes. Transactional integrity, for example, will greatly benefit from any such exercise.
Below is an example usage of a createMutex
function that was written in the aim of introducing a primitive similar to mutex locks to JavaScript.
const { createMutexLock } = require('./mutex');
const acquireLock = createMutexLock();
const someFunctionWithCriticalSection = async () => {
await acquireLock(async () => {
await foo();
await bar();
await baz();
});
};
Promise.all([
someFunctionWithCriticalSection(),
someFunctionWithCriticalSection()
])
.catch(error => { console.error(error); })
const someFunctionWithCriticalSection = async () => {
// These, collectively, represent critical sections
await foo();
await bar();
await baz();
};
Promise.all([
someFunctionWithCriticalSection(),
someFunctionWithCriticalSection()
])
.catch(error => { console.error(error); })