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.00
# p-try
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: p-try
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install p-try`
10
11
## Core Imports
12
13
```javascript
14
import pTry from 'p-try';
15
```
16
17
## Basic Usage
18
19
```javascript
20
import pTry from 'p-try';
21
22
try {
23
const value = await pTry(() => {
24
return synchronousFunctionThatMightThrow();
25
});
26
console.log(value);
27
} catch (error) {
28
console.error(error);
29
}
30
```
31
32
## Capabilities
33
34
### Promise Chain Initialization
35
36
Wraps any function (synchronous or asynchronous) in a Promise, providing consistent error handling regardless of whether the function throws synchronously or rejects asynchronously.
37
38
```javascript { .api }
39
/**
40
* Start a promise chain by wrapping a function in a Promise
41
* @param function_ - The function to run to start the promise chain
42
* @param arguments - Arguments to pass to function_
43
* @returns Promise that resolves with the function's return value or rejects if the function throws
44
*/
45
export default function pTry<ValueType, ArgumentsType extends unknown[]>(
46
function_: (...arguments: ArgumentsType) => PromiseLike<ValueType> | ValueType,
47
...arguments: ArgumentsType
48
): Promise<ValueType>;
49
```
50
51
**Usage Examples:**
52
53
```javascript
54
import pTry from 'p-try';
55
56
// Basic usage with synchronous function
57
const result1 = await pTry(() => {
58
return JSON.parse('{"valid": "json"}');
59
});
60
61
// Handling synchronous errors
62
try {
63
await pTry(() => {
64
throw new Error('Synchronous error');
65
});
66
} catch (error) {
67
console.error('Caught:', error.message);
68
}
69
70
// Working with asynchronous functions
71
const result2 = await pTry(async () => {
72
const response = await fetch('/api/data');
73
return response.json();
74
});
75
76
// Passing arguments to the function
77
const result3 = await pTry((x, y) => x + y, 5, 10);
78
// result3 === 15
79
80
// Mixed sync/async scenarios
81
const processData = (data) => {
82
if (!data) {
83
throw new Error('No data provided'); // Synchronous throw
84
}
85
return Promise.resolve(data.toUpperCase()); // Asynchronous operation
86
};
87
88
try {
89
const processed = await pTry(processData, 'hello world');
90
console.log(processed); // 'HELLO WORLD'
91
} catch (error) {
92
console.error('Processing failed:', error.message);
93
}
94
```
95
96
**Key Features:**
97
98
- **Consistent Error Handling**: Converts synchronous throws to Promise rejections
99
- **Type Safety**: Full TypeScript support with generic type parameters
100
- **Argument Passing**: Supports passing arguments to the wrapped function
101
- **No Performance Overhead**: Minimal wrapper that preserves function behavior
102
- **ES Module**: Uses modern ES module syntax with default export
103
104
**Common Use Cases:**
105
106
1. **Safe JSON Parsing**: Wrap `JSON.parse()` calls to handle malformed JSON consistently
107
2. **Mixed Sync/Async APIs**: Normalize error handling when functions may be either synchronous or asynchronous
108
3. **Promise Chain Starting**: Begin promise chains safely without worrying about synchronous throws
109
4. **Library Integration**: Wrap third-party functions that may throw synchronously