Skip to content
Eugene Lazutkin edited this page Mar 19, 2016 · 3 revisions

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:

timeout.resolve(ms, Deferred)

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 for Promise — 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.

timeout.reject(ms, Deferred)

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.

timeout.Timeout

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.

timeout(Deferred)

When the main function is called with a single argument:

  • Deferred — an optional deferred constructor (realistically Deferred or FastDeferred) or a falsy value for Promise — it will be used to construct internal promises.

It returns an object with following properties:

  • resolve(ms) — like timeout.resolve(ms), but without the second argument, which was already specified.
  • reject(ms) — like timeout.reject(ms), but without the second argument, which was already specified.
  • Timeout — like timeout.Timeout.

Examples

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();