Channel Synchronization in JavaScript

Channel synchronization can be achieved in JavaScript using Promises or async/await. Here’s an example of using a Promise to wait for an asynchronous operation to finish:

const worker = () => {
    return new Promise((resolve) => {
        console.log("working...");
        setTimeout(() => {
            console.log("done");
            resolve();
        }, 1000);
    });
};

async function main() {
    // Start a worker function, getting a promise to notify when it's done
    const done = worker();

    // Wait until we receive a notification that the worker is done
    await done;
}

main();

This is the function we’ll run asynchronously. The returned Promise will be used to notify when this function’s work is done.

In the worker function, we use setTimeout to simulate a delay, similar to the time.Sleep in the original example. After the delay, we log “done” and resolve the Promise.

In the main function, we start the worker function and get a Promise. We then use await to block until the Promise is resolved, which happens when the worker is done.

To run the program:

$ node channel-synchronization.js
working...done

If you removed the await done line from this program, the program would exit before the worker even finished, unless you’re running this in a REPL or an environment that waits for all Promises to settle.

JavaScript doesn’t have built-in constructs exactly equivalent to Go’s channels and goroutines. However, Promises and async/await provide powerful tools for managing asynchronous operations and can be used to achieve similar patterns of synchronization and communication between concurrent operations.