1.1.1 • Published 5 years ago

await-timeout v1.1.1

Weekly downloads
10,506
License
MIT
Repository
github
Last release
5 years ago

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

@amygrooove1/smart-order-router-horiza-fork@real-wagmi/smart-order-router@hypi/hypi@trieb.work/zoho-inventory-tsrpc-pingerswash-smart-router@ersanyakit/smart-order-router@infinitebrahmanuniverse/nolb-awamy_smart_orderrouter@everything-registry/sub-chunk-1191@arthswap/smart-order-router@cryptoalgebra/router@cryptoalgebra/router-2test-dex-smart-order-routersperax-smart-order-routertestbluedex-smart-order-routerthe-playlist-botvoronin-smart-order-routerv-swap-smart-order-router@dotdev/shopify@cryptobadassnpm/smart-order-router@crescentswap/smart-order-router@cytoswap/smart-order-router@daa-zksync/smart-order-router@daiaioz/smart-order-router@danburton/reach-stdlib@colligence/smart-order-router@derpdex/smart-order-router@dooswap/smart-order-router@camp-network/uniswap-smart-order-router@bluedex/smart-order-routerjoule-smart-order-routerkarasb-router@daominhhiep/smart-order-router@sigismund/smart-order-routerdimaa-smart-order-router@nathan2024/up-smart-order-routerstratoswap-smart-order-routeru-smart-order-router-v3udonswap-smart-order-routerudonswap-smart-order-router-v3tokenlauncher-smart-order-router@ape.swap/smart-order-router@aperture_finance/uniswap-smart-order-router@arth-s/smart-order-router@aryze/smart-order-router@atleta-chain/smart-order-router@atleta-chain/smart-order-router-next@atlantiswap/smart-order-router@adobe/plugin-hooks@adrastia-oracle/ethers-fallback-provider@adrastia-oracle/ethers-v6-fallback-provider@airdao/smart-order-router@beincom/smart-order-router@basex-fi/smart-order-router@beal2912/smart-order-router@baseswapfi/custom-order-router@baseswapfi/smart-order-router@biteigen/smart-order-router@bigoceangg/smart-order-router@bulbaswap/smart-order-router@brownpapertickets/shovel@brydge-network/smart-order-router@cheezburgerhq/smart-order-router@chaoswap/smart-order-router@0xinti/smart-order-router@1delta/universal-router@0xelod/smart-order-router@abstractswap/smart-order-router@_etcswap/smart-order-router@aaran1337/smart-order-router@aaran1337/smart-order-router-test@bombswap/smart-order-router@bonsaiswapv3/smart-order-router@deansel/minyami@deliquifiedlabs/smart-order-router@dex-swap/smart-order-router@crust_finance/smart-order-router@darkeagle1236/smart-order-router@dappworks/mimoswap-sdkxooa-sdkwasabi-smart-routeruniswap-smart-order-routerzkflow-smart-order-router@filth/smart-order-router@finstable/smart-order-router@eclips3e3/smart-order-router-susono@eclips3e3/smart-order-router-fugison@eclips3e3/smart-order-router-fujisan@eclips3e3/smart-order-router-maistestsubnet-modded@harshalmaniya/jediswap-smart-order-router@fikaswap/smart-order-router@forge-trade/smart-order-router@hemilabs/smart-order-router@firefly-dex/smart-order-router@florian-s-a-w/smart-order-router@florian-s-a-w/uniswap-smart-order-router@emag3m/smart-order-router@gbex_chain/smart-order-router@gonswap/smart-order-router
1.1.1

5 years ago

1.1.0

5 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.6.0

6 years ago

0.5.0

6 years ago

0.4.0

6 years ago

0.3.0

7 years ago

0.2.0

7 years ago

0.1.6

8 years ago

0.1.5

8 years ago

0.1.4

8 years ago

0.1.3

8 years ago

0.1.2

8 years ago

0.1.1

8 years ago