throw-error-on-timeout

1.1.2 • Public • Published

throw-error-on-timeout

Throw an error (and allow to stop flow) if an async function takes more than a set duration

Installation

npm i --save throw-error-on-timeout

Usage

Initialization

CommonJS modules

For CommonJS modules (require/exports)

const ThrowErrorOnTimeout = require('throw-error-on-timeout');

JavaScript modules

For JavaScript modules (import/export)

import ThrowErrorOnTimeout from 'throw-error-on-timeout';

Instanciation

Instanciate with defined timeout

const timeoutError = new ThrowErrorOnTimeout(1000);

Methods

raceWithTimeout

Method raceWithTimeout executes the async function, that acts in the exact same way as the original function, but throw an error if the race agains timeout is lost.

try {
  const globalResult = await timeoutError.raceWithTimeout(async () => {
    //
    // Put your async function(s) here
    //
    // Any value return here will be returned by
    // the "raceWithTimeout" function (in case of success)
  });
} catch(err) {
  // "err" will be "Async function timeout", if global async function time-outs
  // or the error thrown by the function otherwise.
}

checkExpiration

Method checkExpiration allows to stop flow if the global function has already time-outed.

try {
  const globalResult = await timeoutError.raceWithTimeout(async () => {
    await oneAsyncFunction();

    timeoutError.checkExpiration();

    // Will be executed only if global function has not time-outed yet
    // at the time of the "checkExpiration", the line before
    await anotherAsyncFunction();
  });
} catch(err) {
  // "err" will still be "Async function timeout", if global async function time-outs
}

Lambda use case

This package was initially created in order to handle lambda timeout. Lambda provides a getRemainingTimeInMillis method in the context object that gives the remaining time before lambda timeout. So calling the constructor with that function allows to anticipate lambda timeout:

const promiseTimeout = new PromiseChainTimeoutRejection(context.getRemainingTimeInMillis() - 500);

Re-writing of old "promise-chain-timeout-rejection" package

This package is a re-writing of the "promise-chain-timeout-rejection" package adapted to async/await functions.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
1.1.22latest

Version History

VersionDownloads (Last 7 Days)Published
1.1.22
1.1.00
1.0.01

Package Sidebar

Install

npm i throw-error-on-timeout

Weekly Downloads

3

Version

1.1.2

License

MIT

Unpacked Size

11.4 kB

Total Files

6

Last publish

Collaborators

  • mathieutamer