Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

await-timeout

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

await-timeout

A Promise-based API for setTimeout / clearTimeout

  • 0.2.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
52K
decreased by-13.31%
Maintainers
1
Weekly downloads
 
Created
Source

await-timeout

A Promise-based API for setTimeout / clearTimeout
Build Status Npm version License

Contents

Installation

npm install await-timeout --save

Usage

The example below shows how to set timeout for fetching example.com using ES7 async / await syntax. The code is wrapped into try...finally block that guarantees the timeout will be properly cleared:

import Timeout from 'await-timeout';

async function foo() {
  const timeout = new Timeout();
  try {
    const fetchPromise = fetch('https://example.com');
    const timerPromise = timeout.set(1000, 'Timeout!');
    return await Promise.race([fetchPromise, timerPromise]);
  } catch (e) {
    console.error(e);
  } finally {
    timeout.clear();
  }
}

The same example with .then:

function foo() {
  const timeout = new Timeout();
  return Promise.race([
    fetch('https://example.com'), 
    timeout.set(1000, 'Timeout!')
  ])
  .then(result => {
    timeout.clear();
    return result;
  })
  .catch(e => {
    timeout.clear();
    console.error(e);
  });
}

The same example using Timeout.wrap() has less code:

function foo() {
  const promise = fetch('https://example.com');
  return Timeout.wrap(promise, 1000, 'Timeout!').catch(e => console.error(e));
}

API

new Timeout()

Constructs new timeout instance. It does not start timer but creates variable for timer manipulation.

const timeout = new Timeout();

Note: having separate variable is useful for clearing timeout in finally block

.set(ms, [message]) ⇒ Promise

Starts new timer like setTimeout() and returns promise. The promise will be resolved after ms milliseconds:

const timeout = new Timeout();
timeout.set(1000)
  .then(() => console.log('1000 ms passed.'));

If you need to reject after timeout:

timeout.set(1000)
  .then(() => {throw new Error('Timeout')});

Or reject with custom error:

timeout.set(1000)
  .then(() => {throw new MyTimeoutError()});

The second parameter message is just convenient way to reject with new Error(message):

timeout.set(1000, 'Timeout');
// equivalent to
timeout.set(1000).then(() => {throw new Error('Timeout')});

If you need to just wait some time - use static version of .set():

Timeout.set(1000).then(...);

.wrap(promise, ms, [message]) ⇒ Promise

Wraps promise into timeout that automatically cleared if promise gets fulfilled.

Timeout.wrap(fetch('https://example.com'), 1000, 'Timeout!')
  .catch(e => console.error(e));

.clear()

Clears existing timeout like clearTimeout().

const timeout = new Timeout();
timeout.set(1000)
  .then(() => console.log('This will never be called, because timeout is cleared on the next line'));
timeout.clear();

With ES7 async / await .clear() can be used in finally block:

async function foo() {
  const timeout = new Timeout();
  try {
    // some async stuff
  } finally {
    timeout.clear();
  }
}

Motivation

Before making this library I've researched many similar packages on Npm. But no one satisfied all my needs together:

  1. Convenient way to cancel timeout. I typically use it with Promise.race() and don't want timer to trigger if main promise is fulfilled first.
  2. API similar to setTimeout / clearTimeout. I get used to these functions and would like to have mirror syntax.
  3. Easy rejection of timeout promise. Passing error message should be enough.
  4. No monkey-patching of Promise object.
  5. Zero dependencies.

License

MIT @ Vitaliy Potapov

Keywords

FAQs

Package last updated on 17 Jan 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc