Waitgroups in TypeScript
Our example demonstrates how to wait for multiple asynchronous operations to finish using Promises in TypeScript. This is similar to the concept of WaitGroups in other languages.
To run the program:
In this TypeScript version, we use Promises to manage asynchronous operations. The worker
function is defined as an async function that simulates an expensive task using setTimeout
.
In the main
function, we create an array of Promises, each corresponding to a worker. We then use Promise.all()
to wait for all workers to complete. This is analogous to the WaitGroup.Wait()
in the original example.
Note that the order of workers starting up and finishing is likely to be different for each invocation, just like in the original example.
Unlike the original example, error propagation is straightforward with Promises. If any of the workers throws an error, it will be caught in the main().catch()
block. For more advanced error handling, you could use Promise.allSettled()
instead of Promise.all()
.
TypeScript and JavaScript don’t have built-in constructs exactly equivalent to goroutines, but asynchronous functions and Promises provide similar capabilities for managing concurrent operations.