Skip to main content
Safely executes a function (synchronous or asynchronous) and wraps its result in a Promise. Optionally respects an AbortSignal.

Signature

function attempt<T, Args extends unknown[]>(
  fn: (...args: Args) => T | PromiseLike<T>,
  args?: Args,
  options?: StandardOptions,
): Promise<T>

Parameters

fn
(...args: Args) => T | PromiseLike<T>
required
The function to execute. Can be synchronous or asynchronous.
args
Args
Arguments to pass to the function. Defaults to an empty array.
options
StandardOptions
Execution options.

Returns

A promise that resolves with the result of the function.

Throws

  • AbortError if the signal is aborted before or after execution
  • Any error thrown by the function

Examples

Execute a synchronous function

import { attempt } from '@temelj/async';

const result = await attempt(() => {
  return 42;
});

console.log(result); // 42

Execute an async function

import { attempt } from '@temelj/async';

const result = await attempt(async () => {
  const data = await fetchData();
  return data;
});

Pass arguments to the function

import { attempt } from '@temelj/async';

function add(a: number, b: number) {
  return a + b;
}

const result = await attempt(add, [5, 3]);
console.log(result); // 8

With abort signal

import { attempt } from '@temelj/async';

const controller = new AbortController();

const promise = attempt(
  async () => {
    await delay(1000);
    return 'completed';
  },
  [],
  { signal: controller.signal }
);

// Cancel the operation
controller.abort();

try {
  await promise;
} catch (error) {
  if (error instanceof AbortError) {
    console.log('Operation cancelled');
  }
}

Error handling

import { attempt } from '@temelj/async';

try {
  const result = await attempt(() => {
    throw new Error('Something went wrong');
  });
} catch (error) {
  console.error('Function failed:', error);
}

Build docs developers (and LLMs) love