Start a promise chain by wrapping any function in a Promise with consistent error handling
npx @tessl/cli install tessl/npm-p-try@3.0.0p-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.
npm install p-tryimport pTry from 'p-try';import pTry from 'p-try';
try {
const value = await pTry(() => {
return synchronousFunctionThatMightThrow();
});
console.log(value);
} catch (error) {
console.error(error);
}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:
Common Use Cases:
JSON.parse() calls to handle malformed JSON consistently