Clean Markup

Unified Sync and Async Error Handling with Promise try

Unified Sync and Async Error Handling with Promise try

JavaScript developers wrapping callbacks that might return a plain value, return a Promise, or throw synchronously have long faced an awkward trade-off. Writing Promise.resolve().then(fn) catches synchronous exceptions and converts them into rejected Promises, but it forces fn to wait until the next microtask tick before executing—subtle timing that can alter state ordering or break synchronous DOM assumptions. Conversely, calling new Promise((resolve) => resolve(fn())) runs fn synchronously and captures throws, yet looks noisy and requires wrapping arguments in an extra closure.

Standardized in ECMAScript 2025 and shipped across modern engines in 2025 (Chrome 128+, Firefox 134+, Safari 18.2+, and Node.js 23+), Promise.try(callbackFn, ...args) resolves this ergonomics and timing gap directly in the language specification. It invokes callbackFn immediately in the current execution turn with any supplied arguments, wraps a synchronous return value in a fulfilled Promise, adopts a returned Promise or thenable unchanged, and automatically converts any synchronous throw into a rejected Promise so callers can handle every outcome uniformly through .catch() or try/await.

Example

function parseConfig(rawJson) {
  // May throw synchronously (SyntaxError) or return an object
  return JSON.parse(rawJson);
}

// Executes parseConfig synchronously, but guarantees a Promise return value
Promise.try(parseConfig, '{"featureFlag": true}')
  .then((config) => {
    console.log('Loaded config:', config.featureFlag);
  })
  .catch((error) => {
    console.error('Configuration error:', error.message);
  });

Implementation

/**
 * Safe feature-checked wrapper for ES2025 Promise.try.
 * Falls back to an equivalent synchronous Promise constructor when
 * running in legacy JavaScript runtimes.
 *
 * @template TArgs extends unknown[]
 * @template TResult
 * @param {(...args: TArgs) => TResult | PromiseLike<TResult>} callbackFn
 * @param {...TArgs} args
 * @returns {Promise<Awaited<TResult>>}
 */
export function runSafely(callbackFn, ...args) {
  if (typeof callbackFn !== 'function') {
    return Promise.reject(new TypeError('Expected a callable function'));
  }

  if (typeof Promise.try === 'function') {
    return Promise.try(callbackFn, ...args);
  }

  return new Promise((resolve) => {
    resolve(callbackFn(...args));
  });
}

/**
 * Production task pipeline that accepts both synchronous validators
 * and asynchronous remote checks under one unified Promise chain.
 *
 * @param {string} payload
 * @param {Array<(input: unknown) => unknown | Promise<unknown>>} steps
 * @returns {Promise<{ ok: true, value: unknown } | { ok: false, error: Error }>}
 */
export async function executeValidationPipeline(payload, steps) {
  try {
    let current = await runSafely(JSON.parse, payload);

    for (const step of steps) {
      current = await runSafely(step, current);
    }

    return { ok: true, value: current };
  } catch (err) {
    const error = err instanceof Error ? err : new Error(String(err));
    return { ok: false, error };
  }
}

// Example usage mixing sync validation and async verification
const pipelineSteps = [
  (data) => {
    if (!data || typeof data.userId !== 'string') {
      throw new RangeError('Missing string userId');
    }
    return data;
  },
  async (data) => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    return { ...data, verifiedAt: new Date().toISOString() };
  }
];

executeValidationPipeline('{"userId": "usr_409"}', pipelineSteps).then((result) => {
  if (!result.ok) {
    console.error('Pipeline failed:', result.error.message);
    return;
  }
  console.info('Pipeline succeeded:', result.value);
});

Main Point: ES2025 Promise.try invokes callbacks immediately on the current tick while normalizing both synchronous throws and asynchronous rejections into a single Promise chain.

Credits

Photo by Ajit Singh on Unsplash

← Home