await-timeout

1.1.1 · active · verified Tue Apr 21

await-timeout, currently at version 1.1.1, offers a Promise-based API for handling `setTimeout` and `clearTimeout` in JavaScript, making it particularly useful within `async/await` constructs. It simplifies common asynchronous patterns such as adding timeouts to network requests or other long-running operations. The library provides both static methods like `Timeout.set(ms)` for simple delays and instance methods (`new Timeout().set(ms)`) for more controlled scenarios, including wrapping existing promises with timeouts using `Timeout.wrap(promise, ms, rejectReason)`. A key differentiator is its emphasis on proper resource management, advising the use of `.clear()` within `finally` blocks to prevent unhandled promise rejections or 'unexpected effects' when dealing with `Promise.race`. While a specific release cadence isn't detailed, its stable 1.x version implies a mature and focused utility for precise timeout management in asynchronous codebases.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates using `await-timeout` to add a timeout to a fetch request with `Promise.race` and proper cleanup, alongside a simple static delay.

import Timeout from 'await-timeout';

async function fetchWithTimeoutExample() {
  const timer = new Timeout();
  try {
    console.log('Attempting to fetch data with a 1-second timeout...');
    const dataPromise = fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
    const result = await Promise.race([
      dataPromise,
      timer.set(1000, new Error('Fetch operation timed out!')) // Rejects after 1 second
    ]);

    if (result instanceof Error) {
      throw result; // Propagate the timeout error
    }
    console.log('Data fetched successfully:', result.title);
  } catch (error) {
    console.error('Operation failed:', error.message);
  } finally {
    timer.clear(); // Essential cleanup to prevent resource leaks and 'unexpected effects'
    console.log('Timeout timer cleared.');
  }
}

async function simpleDelayExample() {
  console.log('\nStarting a 500ms delay...');
  await Timeout.set(500); // Static method for a simple awaitable delay
  console.log('Delay finished after 500ms.');
}

fetchWithTimeoutExample();
simpleDelayExample();

view raw JSON →