To create an async timeout in TypeScript, you can use a combination of setTimeout
and Promises.
You can create a function that takes in a time in milliseconds as an argument and returns a Promise that resolves after that time has passed. Here's an example implementation:
index.ts159 chars8 lines
You can use this function in an async/await block to set a timeout. Here's an example:
index.ts338 chars13 lines
Inside the Promise.race
method, we pass in an array of Promises. The first Promise to resolve or reject will be used. In this case, if the async function or promise takes longer than the timeout, the asyncTimeout
Promise will resolve and the code flow will go to the catch
block where you can handle the timeout error.
gistlibby LogSnag