The promise to wrap.
The timeout duration in milliseconds.
A new promise that resolves or rejects based on the original promise and the timeout.
// ES Module
import { timeoutAsyncFn } from '@bnidev/js-utils'
// CommonJS
const { timeoutAsyncFn } = require('@bnidev/js-utils')
// Wrap a fetch request with a timeout
const fetchWithTimeout = timeoutAsyncFn(fetch('https://api.example.com/data'), 5000)
fetchWithTimeout
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error))
// If the fetch does not complete within 5 seconds, it will reject with 'Timeout'
Wraps a promise with a timeout. If the promise does not resolve within the specified time, it rejects with a 'Timeout' error.