Select in TypeScript

Our example demonstrates how to use asynchronous operations and handle multiple promises simultaneously. This is a powerful feature in TypeScript.

import { setTimeout } from 'timers/promises';

async function main() {
    // For our example we'll create two promises.
    const p1 = setTimeout(1000, 'one');
    const p2 = setTimeout(2000, 'two');

    // Each promise will resolve after some amount of time,
    // to simulate e.g. asynchronous API calls executing concurrently.

    // We'll use Promise.race to await both of these values
    // simultaneously, logging each one as it resolves.
    for (let i = 0; i < 2; i++) {
        const result = await Promise.race([p1, p2]);
        console.log('received', result);
    }
}

main().catch(console.error);

We receive the values "one" and then "two" as expected.

$ ts-node select.ts
received one
received two

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.