Waitgroups in JavaScript

Our program demonstrates how to wait for multiple asynchronous operations to finish using Promises in JavaScript. This is conceptually similar to wait groups in other languages.

const worker = async (id) => {
    console.log(`Worker ${id} starting`);
    
    // Simulate an expensive task
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    console.log(`Worker ${id} done`);
};

const main = async () => {
    // This array will hold all our promises
    const promises = [];

    // Launch several workers and add their promises to the array
    for (let i = 1; i <= 5; i++) {
        promises.push(worker(i));
    }

    // Wait for all promises to resolve
    await Promise.all(promises);

    // Note: This approach automatically propagates errors from workers.
    // If you need more advanced error handling, consider using
    // a try-catch block or .catch() on the Promise.all()
};

main().catch(console.error);

To run the program:

$ node waitgroups.js
Worker 1 starting
Worker 2 starting
Worker 3 starting
Worker 4 starting
Worker 5 starting
Worker 1 done
Worker 2 done
Worker 3 done
Worker 4 done
Worker 5 done

In this JavaScript version:

  1. We define an asynchronous worker function that simulates an expensive task using setTimeout.

  2. The main function creates an array of promises, each representing a worker’s execution.

  3. We use Promise.all() to wait for all workers to complete. This is conceptually similar to the WaitGroup.Wait() in the original example.

  4. Error handling is implicit in this Promise-based approach. Any error in a worker will be propagated to the main function.

  5. We wrap the main function call in a .catch() to handle any errors that might occur.

The order of workers starting up and finishing is likely to be different for each invocation, just like in the original example.

Note that JavaScript’s asynchronous nature and Promise-based concurrency model differ from the goroutines and WaitGroups in the original example, but the overall concept of waiting for multiple asynchronous operations to complete is preserved.