Channel Synchronization in TypeScript

Our example demonstrates how to use asynchronous operations to synchronize execution across different parts of a program. In TypeScript, we’ll use Promises to achieve a similar effect.

import { setTimeout } from 'timers/promises';

// This is the function we'll run asynchronously. The
// returned Promise will be used to notify when this
// function's work is done.
async function worker(): Promise<void> {
    process.stdout.write("working...");
    await setTimeout(1000);
    console.log("done");
}

async function main() {
    // Start a worker asynchronous operation
    const done = worker();

    // Block until we receive a notification that the
    // worker has completed
    await done;
}

main().catch(console.error);

To run the program:

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

If you removed the await done line from this program, the program would exit before the worker even started.

In this TypeScript version:

  1. We use an async function worker that returns a Promise, which is analogous to the channel in the original example.

  2. The setTimeout function from the timers/promises module is used to create a delay, similar to time.Sleep in the original.

  3. In the main function, we start the worker asynchronously and then wait for it to complete using await.

  4. We wrap the main function execution in a catch block to handle any errors that might occur during the asynchronous operations.

This approach provides a way to synchronize asynchronous operations in TypeScript, similar to how channels are used for goroutine synchronization in the original example.