await-timeout
A Promise-based API for setTimeout / clearTimeout
Contents
Installation
npm install await-timeout --save
Usage
-
Just wait some time:
;// wait 1000 ms and resolveawait Timeout;// wait 1000 ms and reject with 'Timeout!'await Timeout; -
Use
Timeout
instance insidetry...finally
block to make proper cleanup:;const timer = ;tryawait Promise;finallytimerclear;Without a timer cleanup you may get unexpected effects in you code - as all promises in
Promise.race
are get fulfilled.
API
new Timeout()
Constructs new timeout instance. It does not start timer but creates variable for timer manipulation.
const timer = ;
Note: having separate
timer
variable is useful for clearing timeout infinally
block
Promise
.set(delay, [rejectReason]) ⇒ Starts new timer like setTimeout()
and returns promise. The promise will be resolved after delay
milliseconds:
const timer = ;timer ;
If you provide rejectReason
- a timer promise will be rejected with specified reason:
// rejects with Error: Timeout after 1000 ms:timer; // above is actually shortcut for:timer;
If you need to just wait some time - use static version of .set()
:
await Timeout;
Promise
.wrap(promise, delay, [rejectReason]) ⇒ Wraps existing promise with timeout:
- returned promise automatically rejected after timeout
- timeout automatically cleared if main promise resolves first
{ const promise = ; return Timeout;}
Actually it is a shortcut for:
{ const timer = ; try const promise = ; return await Promise; finally timerclear; }
.clear()
Clears existing timeout like clearTimeout()
.
const timer = ;timer ;timerclear;
With ES7 async / await .clear()
can be used in finally
block:
{ const timer = ; try // some async stuff finally timerclear; }
?Number|?Timeout
.id ⇒ Returns result of setTimeout
call. That is Number
timeout id in browser
and Timeout instance in Node.js.
?Number
.delay ⇒ Returns last delay value used. Delay is useful for generating reject reason:
const timer = ;timer;
Motivation
Before making this library I've researched several similar packages on Npm. But no one satisfied all my needs together:
- Convenient way to cancel timeout. I typically use it with Promise.race() and don't want timer to trigger if main promise is resolved first.
- API similar to
setTimeout
/clearTimeout
. I get used to these functions and would like to have mirror syntax. - Easy rejection of timeout promise. Passing error message should be enough.
- No monkey-patching of Promise object.
- Zero dependencies.
Related resources
- The right way to clear timeout in Promise.race()
- Applying a timeout to your promises
- How to make a promise from setTimeout
- Is there a version of setTimeout that returns an ES6 promise?
License
MIT @ Vitaliy Potapov