Goroutines in TypeScript

Based on the provided input, here is the translation of the given example into TypeScript.

Goroutines (equivalent: Asynchronous Functions in TypeScript)

A goroutine is a lightweight thread of execution.

Example Code

function f(from: string) {
    for (let i = 0; i < 3; i++) {
        console.log(`${from}: ${i}`);
    }
}

(async () => {
    // Suppose we have a function call `f(s)`. Here’s how
    // we’d call that in the usual way, running it
    // synchronously.

    f("direct");

    // To invoke this function as an asynchronous function, use
    // `setTimeout` or similar. This new asynchronous execution will run
    // concurrently with the calling one.

    setTimeout(() => f("asynchronous"), 0);

    // You can also start an asynchronous function for an anonymous
    // function call.

    setTimeout(() => {
        console.log("going");
    }, 0);

    // Our two function calls are running asynchronously now.
    // Wait for them to finish using `Promise`s (for a more robust approach, combine them with `Promise.all`).

    await new Promise(resolve => setTimeout(resolve, 1000));

    console.log("done");
})();

Explanation

When we run this program, we see the output of the blocking call first, then the output of the asynchronous function calls. The output from asynchronous functions may be interleaved because they are being executed concurrently by the JavaScript runtime.

To see the output, simply run the TypeScript code using:

$ ts-node yourfile.ts

Or compile it to JavaScript and run it with Node.js:

$ tsc yourfile.ts
$ node yourfile.js

Output

$ ts-node yourfile.ts
direct: 0
direct: 1
direct: 2
asynchronous: 0
going
asynchronous: 1
asynchronous: 2
done

Next, we’ll look at a complement to asynchronous functions: Promises and async/await in TypeScript.