This library extends standard ECMAScript Promises with the timeout functionality and works in any browser supporting Promises or Node.js environment.
- Converting standard Fetch Promise to TimedPromise with the 3s timeout
let data = await new TimedPromise( fetch('http://example.com/movies.json') )
.then( response => response.json() )
.then( json => { return { ok: true, json } })
.timeout( 3000, { ok: false, error: 'fetch-timeouted' })
.catch( error => { return { ok: false, error } });
- Creating new TimedPromise with the 3s timeout
let data = await new TimedPromise( ( resolve, reject, timeout ) =>
{
console.log( `Fetch timeout set to ${timeout}ms` );
fetch('http://example.com/movies.json')
.then( response => response.json() )
.then( json => resolve({ ok: true, json }) )
.catch( error => reject({ ok: false, error }) );
})
.timeout( 3000, { ok: false, error: 'fetch-timeouted' })
.catch( error => error );
Standard JavaScript Promises
does not provide any support for timeouts - failing the Promise once the timer is elapsed. There are many solutions how to simulate such functionality - for example creating new Promise with the reject callback triggered by the setTimeout
function or using Promise.race()
method for the original Promise and a new Promise resolved by the setTimeout
function.
npm install --save liqd-timed-promise
or include script for a browser release
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/radixxko/liqd-timed-promise/dist/timed_promise.min.js"></script>
executor
{Function|Promise}
timeout_ms
{Number} Timeout for the Promise in milisecondsreason
{Any} Exception thrown by the Promise when it is not resolved within a timeout- defaults to {String} 'timeout'
catchable_by_parent
{Boolean} Determines whether a timeout exception can be catched and resolved by a preceding catch in the Promise chain
Returns this
.
Returns a number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the TimedPromise creation.
Returns a number representing the milliseconds elapsed since the TimedPromise creation.
Returns a number representing the milliseconds remaining until the TimedPromise timeout.
Returns new TimedPromise
p.then( onFulfilled[, onRejected] );
p.then( ( value, remaining_ms ) =>
{
// fulfillment
}, ( reason, remaining_ms ) =>
{
// rejection
});
Returns new TimedPromise
p.catch( onRejected );
p.catch( ( reason, remaining_ms ) =>
{
// rejection
});