TimedPromise: ECMAScript 6+ class extending standard JavaScript Promises with timeout functionality
Sneak Peek
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 ;
- Creating new TimedPromise with the 3s timeout
let data = await { console; ;};
Motivation
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.
Table of Contents
Installing
npm install --save liqd-timed-promise
or include script for a browser release
Class: TimedPromise extends Promise
new TimedPromise( executor )
executor
{Function|Promise}
TimedPromise.timeout( timeout_ms[, reason = 'timeout'[, catchable_by_parent = false]] )
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
.
TimedPromise.created()
Returns a number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and the TimedPromise creation.
TimedPromise.elapsed()
Returns a number representing the milliseconds elapsed since the TimedPromise creation.
TimedPromise.remaining()
Returns a number representing the milliseconds remaining until the TimedPromise timeout.
TimedPromise.then( onFulfilled[, onRejected] )
Returns new TimedPromise
p; p;
TimedPromise.catch( onRejected] )
Returns new TimedPromise
p; p;