timeout
Create a promise that rejects after some time
246 bytes
Usage
The timeout
function creates a promise that rejects after a specified delay, with an optional custom error message or error function.
The default error is a TimeoutError
with the message “Operation timed out”.
import * as _ from 'radashi'
// Rejects after 1 second with a default TimeoutErrorawait _.timeout(1000)
// Rejects after 1 second with a custom TimeoutError messageawait _.timeout(1000, 'Custom timeout message')
// Rejects after 1 second with a custom error typeawait _.timeout(1000, () => new Error('Custom error'))
Example with Promise.race
One of the most useful ways to use _.timeout
with Promise.race
to set a timeout for an asynchronous operation.
import * as _ from 'radashi'
const someAsyncTask = async () => { await _.sleep(10_000) return 'Task completed'}
// Race between the async task and a timeout of 1 secondawait Promise.race([someAsyncTask(), _.timeout(1000, 'Task took too long')])