or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-p-try

Start a promise chain by wrapping any function in a Promise with consistent error handling

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/p-try@3.0.x

To install, run

npx @tessl/cli install tessl/npm-p-try@3.0.0

index.mddocs/

p-try

p-try provides a simple utility function for starting promise chains by wrapping any function (synchronous or asynchronous) in a Promise. It serves as a ponyfill for Promise.resolve() when dealing with functions that may throw synchronously, ensuring consistent promise-based error handling.

Package Information

  • Package Name: p-try
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install p-try

Core Imports

import pTry from 'p-try';

Basic Usage

import pTry from 'p-try';

try {
    const value = await pTry(() => {
        return synchronousFunctionThatMightThrow();
    });
    console.log(value);
} catch (error) {
    console.error(error);
}

Capabilities

Promise Chain Initialization

Wraps any function (synchronous or asynchronous) in a Promise, providing consistent error handling regardless of whether the function throws synchronously or rejects asynchronously.

/**
 * Start a promise chain by wrapping a function in a Promise
 * @param function_ - The function to run to start the promise chain
 * @param arguments - Arguments to pass to function_
 * @returns Promise that resolves with the function's return value or rejects if the function throws
 */
export default function pTry<ValueType, ArgumentsType extends unknown[]>(
    function_: (...arguments: ArgumentsType) => PromiseLike<ValueType> | ValueType,
    ...arguments: ArgumentsType
): Promise<ValueType>;

Usage Examples:

import pTry from 'p-try';

// Basic usage with synchronous function
const result1 = await pTry(() => {
    return JSON.parse('{"valid": "json"}');
});

// Handling synchronous errors
try {
    await pTry(() => {
        throw new Error('Synchronous error');
    });
} catch (error) {
    console.error('Caught:', error.message);
}

// Working with asynchronous functions
const result2 = await pTry(async () => {
    const response = await fetch('/api/data');
    return response.json();
});

// Passing arguments to the function
const result3 = await pTry((x, y) => x + y, 5, 10);
// result3 === 15

// Mixed sync/async scenarios
const processData = (data) => {
    if (!data) {
        throw new Error('No data provided'); // Synchronous throw
    }
    return Promise.resolve(data.toUpperCase()); // Asynchronous operation
};

try {
    const processed = await pTry(processData, 'hello world');
    console.log(processed); // 'HELLO WORLD'
} catch (error) {
    console.error('Processing failed:', error.message);
}

Key Features:

  • Consistent Error Handling: Converts synchronous throws to Promise rejections
  • Type Safety: Full TypeScript support with generic type parameters
  • Argument Passing: Supports passing arguments to the wrapped function
  • No Performance Overhead: Minimal wrapper that preserves function behavior
  • ES Module: Uses modern ES module syntax with default export

Common Use Cases:

  1. Safe JSON Parsing: Wrap JSON.parse() calls to handle malformed JSON consistently
  2. Mixed Sync/Async APIs: Normalize error handling when functions may be either synchronous or asynchronous
  3. Promise Chain Starting: Begin promise chains safely without worrying about synchronous throws
  4. Library Integration: Wrap third-party functions that may throw synchronously