Timeouts in TypeScript
Here’s the TypeScript translation of the Go code example for timeouts:
Timeouts are important for programs that connect to external resources or that otherwise need to bound execution time. Implementing timeouts in TypeScript is straightforward using Promises and setTimeout
.
Running this program shows the first operation timing out and the second succeeding.
In this TypeScript version:
We use
async/await
syntax for handling asynchronous operations, which is more idiomatic in TypeScript than using callbacks.Instead of channels, we use Promises. The
externalCall
function returns a Promise that resolves after 2 seconds.We implement the timeout using
Promise.race
. This function takes an array of Promises and resolves or rejects as soon as one of the Promises in the array resolves or rejects.We use
setTimeout
from thetimers/promises
module, which returns a Promise that resolves after the specified delay.Error handling is done using try/catch blocks, which is the standard way to handle errors in asynchronous TypeScript code.
This approach provides similar functionality to the original example, allowing us to set timeouts for asynchronous operations in a clear and readable manner.