-
Notifications
You must be signed in to change notification settings - Fork 1
async.timeout
This module provides a generalized timeout functionality. It can resolve or reject a promise after a given timeout (in milliseconds). It can be instrumented to use internally a deferred or a standard Promise
.
The module returns a function with following properties:
This function takes two arguments:
-
ms
— a timeout in milliseconds as a natural number. -
Deferred
— an optional deferred constructor (realistically Deferred or FastDeferred) or a falsy value forPromise
— it will be used to construct internal promises.
It returns a promise, which will be resolved after ms
milliseconds with value ms
. If a cancellable deferred is used, this operation can be safely cancelled.
This function takes the same arguments as timeout.resolve()
described above.
It returns a promise, which will be rejected after ms
milliseconds with value new (timeout.Timeout)(ms)
. If a cancellable deferred is used, this operation can be safely cancelled.
A constructor that is used to create error instances for rejected promises. Those instances have one property timeout
, which is set to a number of milliseconds used to reject a promise. It is exposed mostly to use with instanceof
operator.
When the main function is called with a single argument:
-
Deferred
— an optional deferred constructor (realistically Deferred or FastDeferred) or a falsy value forPromise
— it will be used to construct internal promises.
It returns an object with following properties:
-
resolve(ms)
— liketimeout.resolve(ms)
, but without the second argument, which was already specified. -
reject(ms)
— liketimeout.reject(ms)
, but without the second argument, which was already specified. -
Timeout
— liketimeout.Timeout
.
Restrict an asynchronous operation with a timeout using the standard Promise
:
var timeout = require('heya-async/timeout');
Promise.race([asyncFun(), timeout.reject(100)]).
then(function (value) { console.log('Success:', value); return value; }).
catch(function (error) {
if (error instanceof timeout.Timeout) {
console.log('Timeout after', error.timeout, 'milliseconds');
} else {
console.log('Failure:', error);
}
});
Create and cancel timeout using FastDeferred:
var FastDeferred = require('heya-async/FastDeferred');
var timeout = require('heya-async/timeout');
var promise = timeout(FastDeferred).resolve(1000);
promise.done(function (ms) {
console.log('Delayed by', ms, 'milliseconds.');
});
// ...
promise.cancel();