WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Guru · question 87 of 100

What are some advanced concurrency patterns in JavaScript for managing complex asynchronous operations or parallel computing?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

Concurrency patterns in JavaScript are essential to manage asynchronous operations effectively and efficiently. Concurrency patterns help developers avoid problems such as race conditions, deadlocks, and starvation when multiple processes are running in parallel. Here are some of the advanced concurrency patterns in JavaScript:

Worker threads: Worker threads are a way to run JavaScript code in parallel, in a separate thread from the main thread. This allows developers to offload computationally intensive tasks to a worker thread, freeing up the main thread for other tasks. Worker threads use a message passing mechanism to communicate with the main thread, which allows them to share data without causing race conditions.

Here’s an example of using worker threads in Node.js:

    const { Worker } = require('worker_threads');
    
    function runWorker(workerData) {
        return new Promise((resolve, reject) => {
            const worker = new Worker('./worker.js', { workerData });
            worker.on('message', resolve);
            worker.on('error', reject);
            worker.on('exit', (code) => {
                if (code !== 0)
                reject(new Error(`Worker stopped with exit code ${code}`));
            });
        });
    }
    
    async function main() {
        const result = await runWorker({ some: 'data' });
        console.log(result);
    }

Futures/Promises: Futures/Promises are a concurrency pattern that allows developers to represent a value that will be available at some point in the future. Promises have become a standard feature of JavaScript and are widely used to handle asynchronous operations.

Here’s an example of using Promises in JavaScript:

    function fetchData() {
        return new Promise((resolve, reject) => {
            // some asynchronous operation
            setTimeout(() => {
                resolve('data');
            }, 1000);
        });
    }
    
    fetchData().then((result) => {
        console.log(result);
    });

Reactive programming: Reactive programming is a programming paradigm that allows developers to model data streams and events as observable sequences. Reactive programming is particularly useful for handling real-time data and events, such as user input or sensor data.

Here’s an example of using reactive programming with RxJS:

    import { fromEvent } from 'rxjs';
    
    const button = document.querySelector('#myButton');
    const click$ = fromEvent(button, 'click');
    
    click$.subscribe(() => {
        console.log('Button clicked');
    });

Mutexes and Semaphores: Mutexes and semaphores are concurrency patterns that allow developers to manage access to shared resources in a synchronized way. Mutexes are used to allow only one thread to access a shared resource at a time, while semaphores can allow multiple threads to access a shared resource, up to a certain limit.

Here’s an example of using a mutex in JavaScript:

    class Mutex {
        constructor() {
            this.locked = false;
            this.waiting = [];
        }
        
        async lock() {
            if (!this.locked) {
                this.locked = true;
            } else {
                await new Promise((resolve) => this.waiting.push(resolve));
                await this.lock();
            }
        }
        
        unlock() {
            if (this.waiting.length > 0) {
                const resolve = this.waiting.shift();
                resolve();
            } else {
                this.locked = false;
            }
        }
    }
    
    const mutex = new Mutex();
    
    async function doSomething() {
        await mutex.lock();
        try {
            // critical section
        } finally {
            mutex.unlock();
        }
    }

These are some of the advanced concurrency patterns in JavaScript. Understanding these patterns and knowing when to use them can help developers create efficient and scalable applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics