All Projects → vitalets → Await Timeout

vitalets / Await Timeout

A Promise-based API for setTimeout / clearTimeout

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Await Timeout

Rsup Progress
❤️ A simple progress bar with promises support
Stars: ✭ 290 (-28.22%)
Mutual labels:  promise
Promise Fun
Promise packages, patterns, chat, and tutorials
Stars: ✭ 3,779 (+835.4%)
Mutual labels:  promise
Fun Task
Abstraction for managing asynchronous code in JS
Stars: ✭ 363 (-10.15%)
Mutual labels:  promise
Promise
Ultra-performant Promise implementation in Python
Stars: ✭ 297 (-26.49%)
Mutual labels:  promise
Express Promise
❤️ Middleware for easy rendering of async Query results.
Stars: ✭ 320 (-20.79%)
Mutual labels:  promise
P Iteration
Utilities that make array iteration easy when using async/await or Promises
Stars: ✭ 337 (-16.58%)
Mutual labels:  promise
Yaku
A lightweight promise library
Stars: ✭ 276 (-31.68%)
Mutual labels:  promise
Post Me
📩 Use web Workers and other Windows through a simple Promise API
Stars: ✭ 398 (-1.49%)
Mutual labels:  promise
Vuejs Dialog
A lightweight, promise based alert, prompt and confirm dialog
Stars: ✭ 327 (-19.06%)
Mutual labels:  promise
Angular Admin
🔏Admin client for surmon.me blog powered by @angular and Bootstrap4
Stars: ✭ 352 (-12.87%)
Mutual labels:  promise
Evt
💧EventEmitter's typesafe replacement
Stars: ✭ 305 (-24.5%)
Mutual labels:  promise
Aigle
🦅 Aigle is an ideal promise library which is faster and more efficient than other libraries. It is a production-ready library that implements the Promise A+ standard.
Stars: ✭ 318 (-21.29%)
Mutual labels:  promise
Magicmusic
🎵帅气的手机端音乐播放器(vue vue-router vuex flex ...)
Stars: ✭ 350 (-13.37%)
Mutual labels:  promise
Future
Streamlined Future<Value, Error> implementation
Stars: ✭ 291 (-27.97%)
Mutual labels:  promise
Replace In File
A simple utility to quickly replace contents in one or more files
Stars: ✭ 369 (-8.66%)
Mutual labels:  promise
Mappersmith
is a lightweight rest client for node.js and the browser
Stars: ✭ 282 (-30.2%)
Mutual labels:  promise
When Dom Ready
$(document).ready() for the 21st century
Stars: ✭ 336 (-16.83%)
Mutual labels:  promise
Octokat.js
Github API Client using Promises or callbacks. Intended for the browser or NodeJS.
Stars: ✭ 401 (-0.74%)
Mutual labels:  promise
Pagarme Js
💛 Pagar.me's JavaScript API
Stars: ✭ 370 (-8.42%)
Mutual labels:  promise
Ws
⚠️ Deprecated - (in favour of Networking) ☁️ Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)
Stars: ✭ 352 (-12.87%)
Mutual labels:  promise

await-timeout

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

Contents

Installation

npm install await-timeout --save

Usage

  1. Just wait some time:

    import Timeout from 'await-timeout';
    
    // wait 1000 ms and resolve
    await Timeout.set(1000);
    
    // wait 1000 ms and reject with 'Timeout!'
    await Timeout.set(1000, 'Timeout!');
    
  2. Use Timeout instance inside try...finally block to make proper cleanup:

    import Timeout from 'await-timeout';
    
    const timer = new Timeout();
    try {
      await Promise.race([
        fetch('https://example.com'),
        timer.set(1000, 'Timeout!')
      ]);
    } finally {
      timer.clear();
    }
    

    Without a timer cleanup you may get unexpected effects in you code - as all promises in Promise.race are get fulfilled.

API

new Timeout()

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

const timer = new Timeout();

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

.set(delay, [rejectReason]) ⇒ Promise

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

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

If you provide rejectReason - a timer promise will be rejected with specified reason:

// rejects with Error: Timeout after 1000 ms:
timer.set(1000, 'Timeout after 1000 ms');
  
// above is actually shortcut for:
timer.set(1000).then(() => Promise.reject(new Error('Timeout after 1000 ms')));  

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

await Timeout.set(1000);

.wrap(promise, delay, [rejectReason]) ⇒ Promise

Wraps existing promise with timeout:

  • returned promise automatically rejected after timeout
  • timeout automatically cleared if main promise resolves first
async function fetchWithTimeout() {
  const promise = fetch('https://example.com');
  return Timeout.wrap(promise, 1000, 'Timeout');
}

Actually it is a shortcut for:

async function fetchWithTimeout() {
    const timer = new Timeout();
    try {
      const promise = fetch('https://example.com');
      return await Promise.race([
        promise,
        timer.set(1000, 'Timeout')
      ]);
    } finally {
      timer.clear();
    }
}

.clear()

Clears existing timeout like clearTimeout().

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

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

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

.id ⇒ ?Number|?Timeout

Returns result of setTimeout call. That is Number timeout id in browser and Timeout instance in Node.js.

.delay ⇒ ?Number

Returns last delay value used. Delay is useful for generating reject reason:

const timer = new Timeout();
timer.set(1000, () => new Error(`Timeout: ${timer.delay}`));

Motivation

Before making this library I've researched several 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 resolved 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].