1.1.1 • Published 4 years ago

await-timeout v1.1.1

Weekly downloads
10,506
License
MIT
Repository
github
Last release
4 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-2@eclips3e3/smart-order-router-fugison@eclips3e3/smart-order-router-fujisan@eclips3e3/smart-order-router-maistestsubnet-modded@eclips3e3/smart-order-router-susonowasabi-smart-routertokenlauncher-smart-order-routerthe-playlist-bottestbluedex-smart-order-routertest-dex-smart-order-router@emag3m/smart-order-router@fairdex/smart-order-router@gbex_chain/smart-order-router@genesisprotocol/smart-order-routerv-swap-smart-order-routeruniswap-smart-order-router@intrinsic-network/smart-order-router@intimefinance/smart-order-router@itdeltalabs/bunnyswap-smart-order-router@itdeltalabs/smart-order-router@itdeltalabs/trustdex-smart-order-routerzkflow-smart-order-router@escswap/smart-order-router@hemilabs/smart-order-routerorder412678696orangemio-smart-order-routerdfyn-smart-order-routerracetime-botring-smart-order-routerrtv-serverrtvshady-smart-order-routerskill-dev-proxysmart-order-routersmart-order-router-arbidexsmart-order-router-metapadsmart-order-router-obasesmart-order-router-patchedsmart-order-router-zkevmsmart-order-router-zknetsmart412678696smbc-react-componentssperax-smart-order-router@monocerus/smart-order-router@matterlabs/uniswap-smart-order-router@kevinss/smart-order-router@lvsjack/smart-order-router@miljan9602/smart-order-router@lucoadam1/smart-order-router@orbitalapes/smart-order-router@mrtruongleo/uniswap-smart-order-router@monoswap-labs/smart-order-router@moraswap/smart-order-routerxooa-sdk@gfxlabs/uniswap-smart-order-router@finstable/smart-order-router@filth/smart-order-router@fikaswap/smart-order-router@firefly-dex/smart-order-router@gonswap/smart-order-router@florian-s-a-w/smart-order-router@florian-s-a-w/uniswap-smart-order-router@forge-trade/smart-order-router@manoswap/smart-order-router@mantle-swap/smart-order-router@jalaswap/smart-order-router@daominhhiep/smart-order-router@sigismund/smart-order-routerpancake-routerpanaromaswap_smartorderrouterpancakeswap-bsc-smart-order-routerold-few-smart-order-routerpolkadot-node-apidmode-smart-order-routerdimaa-smart-order-routerquickswap-smart-order-routerdelta-selfbotpuppeteer-vcrpals_smart_order_router@ngduythao/smart-order-router@nixiangyu/smart-order-router@nixiangyu/smart-order-router-01@psdk/frame-ota@offsetcarbon/smart-order-router@s6nougat/smart-order-router@reach-sh/stdlib@myunidavid/smartorderrouter@planq-fi/smart-order-router
1.1.1

4 years ago

1.1.0

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.6.0

5 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.0

6 years ago

0.2.0

6 years ago

0.1.6

6 years ago

0.1.5

6 years ago

0.1.4

6 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago