Giter Site home page Giter Site logo

await-timeout's Introduction

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 usage of timeout with ES7 async / await in try...finally block. It guarantees that timeout will be cleared in case of fetch success or any error:

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!');
    const response = await Promise.race([fetchPromise, timerPromise]);
  } catch (e) {
    console.error(e);
  } finally {
    timeout.clear();
  }
}

The same example using .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);
  });
}

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

.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.

Related resources

License

MIT @ Vitaliy Potapov

await-timeout's People

Contributors

vitalets avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.