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

This module provides a generalized timeout functionality. It can resolve or reject a promise after a given timeout (in milliseconds) with a given value (or a predefined object). It can be instrumented with a deferred or a standard Promise.

The module returns a function that takes a single argument: an optional deferred constructor (realistically Deferred or FastDeferred) or a falsy value for Promise — it will be used to construct internal promises. The function returns a fully instrumented function that takes up to three arguments:

  • ms — a timeout in milliseconds as a positive number.
  • uncaught — an optional argument described in Deferred as catchUnhandled or resolve() and reject().
  • resolveTo — an optional value to use to resolve/reject a promise. If it is not specified, or undefined, TimeoutError object will be constructed, and used for this purpose. Its property timeout will be set to ms value.

When this function is invoked, the promise returned by it will be rejected after a timeout.

The function defined two properties for convenience:

  • resolve() — a function to return a promise, which will be resolved after a timeout.
  • reject() — a function to return a promise, which will be rejected after a timeout. Essentially it is the same as the main function.

These two functions have the same interface as the main function.

Example:

// restrict an asynchronous operation with a timeout

var timeout = require('heya-async/timeout')();

var promise = asyncFun();

Promise.race([promise, timeout(100)]).
  then(function (value) { console.log('Success:', value); return value; }).
  catch(function (error) {
    if (typeof error == 'object' && typeof error.timeout == 'number') {
      console.log('Timeout after', error.timeout, 'milliseconds');
    } else {
      console.log('Failure:', error);
    }
  });