Select in TypeScript
Our example demonstrates how to use asynchronous operations and handle multiple promises simultaneously. This is a powerful feature in TypeScript.
We receive the values "one"
and then "two"
as expected.
Note that the total execution time is only ~2 seconds since both the 1 and 2 second timeouts execute concurrently.
In this TypeScript example, we use Promise.race()
to achieve similar functionality to Go’s select
statement. Promise.race()
returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
We use the setTimeout
function from the timers/promises
module, which returns a promise that resolves after the specified delay. This simulates asynchronous operations like API calls.
The for
loop runs twice, each time waiting for either p1
or p2
to resolve. On the first iteration, p1
resolves first (after 1 second), and on the second iteration, p2
resolves (after 2 seconds total).
This approach allows us to handle multiple asynchronous operations concurrently, similar to Go’s goroutines and channels, but using TypeScript’s promise-based asynchronous model.