1.1.1 • Published 6 years ago

await-timeout v1.1.1

Weekly downloads
10,506
License
MIT
Repository
github
Last release
6 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@camp-network/uniswap-smart-order-router@bluedex/smart-order-routerjoule-smart-order-routerkarasb-routerhermes-smart-order-routerheadless-integrationlogger-remotelolotrgeek-smart-order-routermaia-smart-order-routerlampros-sorlayerizekonxtract@waterfor9/smart-order-router@waterfor9/smart-order-router-old@warpgatex/warp-smart-order-router@web3auth/smart-order-router@weav3npm/smart-order-router@woafflation/smart-order-router@wunsz-4soft/smart-order-router@xeiswap/smart-order-router@x1swap/smart-order-router@xarmian/stdlib@xlayerswap/smart-order-router@xbacked-dao/xbacked-contracts@tryethernal/smart-order-router@trieb.work/zoho-ts@trieb.work/lexoffice-ts@uniswapfoundation/smart-order-router@uniswap/smart-order-router@totality-fi/smart-order-router@tokamak-network/tokamak-smart-order-router@toadsarah/smart-order-router@toadsarah/smart-order-router-spooky@tmychain/smart-order-router@tpvinh/smart-order-router@vinhtruong/smart-order-router@vivektamilarasan/smart-order-router@votopia/smart-order-router@vanadex/smart-order-router@xspswap/smart-order-router@xswap-v3/smart-order-router@xenswap/smart-order-router@yumyumswap/smart-order-router@xverseprojects/smart-order-router@yodlpay/smart-order-router@ziadex/smart-order-router@tendieswap/uniswap-smart-order-routeralmighty-uni@zoralabs/uniswap-smart-order-routeradanize-wallet-utilsarsenswap-smart-order-router@atlantiswap/smart-order-router@atleta-chain/smart-order-router@atleta-chain/smart-order-router-next@itdeltalabs/bunnyswap-smart-order-router@itdeltalabs/smart-order-router@itdeltalabs/trustdex-smart-order-router@gonswap/smart-order-router@1delta/universal-router@0xelod/smart-order-router@harshalmaniya/jediswap-smart-order-router@0xinti/smart-order-router@0xthoth/smart-order-router@aaran1337/smart-order-router@aaran1337/smart-order-router-test@_etcswap/smart-order-router@atleta-chain-templ/smart-order-router@abstractswap/smart-order-router@airdao/smart-order-router@airdao/astra-smart-order-router@adrastia-oracle/ethers-fallback-provider@adrastia-oracle/ethers-v6-fallback-provider@eclips3e3/smart-order-router-fugison@eclips3e3/smart-order-router-fujisan@eclips3e3/smart-order-router-maistestsubnet-modded@eclips3e3/smart-order-router-susono@adobe/plugin-hooks@crescentswap/smart-order-router@crust_finance/smart-order-router@colligence/smart-order-router@alicercedigital/smart-order-router
1.1.1

6 years ago

1.1.0

6 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

8 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