0
# P-Lazy
1
2
P-Lazy is a specialized Promise subclass that implements lazy evaluation for promise execution. It defers the execution of the promise executor function until the promise is actually used through methods like await, `.then()`, `.catch()`, or `.finally()`. This optimization is particularly valuable for expensive operations that may not always be needed, allowing developers to create promises that only consume resources when their results are actually required.
3
4
## Package Information
5
6
- **Package Name**: p-lazy
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES Modules)
9
- **Installation**: `npm install p-lazy`
10
11
## Core Imports
12
13
```javascript
14
import PLazy from "p-lazy";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const PLazy = require("p-lazy");
21
```
22
23
## Basic Usage
24
25
```javascript
26
import PLazy from "p-lazy";
27
28
// Create a lazy promise that won't execute until needed
29
const lazyPromise = new PLazy(resolve => {
30
console.log("This expensive operation only runs when the promise is used");
31
someHeavyOperation(resolve);
32
});
33
34
// The executor hasn't run yet
35
console.log("Promise created, but executor not called");
36
37
// Now the executor runs
38
const result = await lazyPromise;
39
console.log(result);
40
```
41
42
## Architecture
43
44
P-Lazy extends the native Promise class while implementing lazy evaluation:
45
46
- **Lazy Execution**: The executor function is not called until the promise is accessed via `.then()`, `.catch()`, `.finally()`, or `await`
47
- **Promise Compatibility**: Full compatibility with Promise API and can be used anywhere a Promise is expected
48
- **Single Execution**: Once triggered, the internal promise is cached and reused for subsequent operations
49
- **Type Safety**: Full TypeScript support with generic type parameter
50
51
## Capabilities
52
53
### PLazy Constructor
54
55
Creates a new lazy promise with deferred execution.
56
57
```javascript { .api }
58
/**
59
* Create a lazy promise that defers execution until it's awaited or when
60
* .then(), .catch(), or .finally() is called
61
* @param executor - Function with signature (resolve, reject) => void
62
*/
63
constructor(executor: (resolve: Function, reject: Function) => void);
64
```
65
66
**Usage Example:**
67
68
```javascript
69
const lazyPromise = new PLazy((resolve, reject) => {
70
setTimeout(() => {
71
resolve("Heavy computation result");
72
}, 1000);
73
});
74
75
// Executor hasn't run yet
76
await someOtherWork();
77
78
// Now executor runs and waits 1 second
79
const result = await lazyPromise;
80
```
81
82
### Static Factory Methods
83
84
Factory methods for creating lazy promises from various sources.
85
86
```javascript { .api }
87
/**
88
* Create a PLazy promise from a promise-returning or async function
89
* @param function_ - Function returning a value or Promise
90
* @returns PLazy promise that will execute the function when accessed
91
*/
92
static from(function_: () => any): PLazy;
93
94
/**
95
* Create a PLazy promise that is resolved with the given value
96
* @param value - Value to resolve with
97
* @returns PLazy promise resolved with the value
98
*/
99
static resolve(value: any): PLazy;
100
101
/**
102
* Create a PLazy promise that is rejected with the given reason
103
* @param error - Error or reason for rejection
104
* @returns PLazy promise rejected with the error
105
*/
106
static reject(error: any): PLazy;
107
```
108
109
**Usage Examples:**
110
111
```javascript
112
// Create from function
113
const lazyFromFunc = PLazy.from(async () => {
114
const data = await fetchExpensiveData();
115
return processData(data);
116
});
117
118
// Create resolved lazy promise
119
const lazyResolved = PLazy.resolve("immediate value");
120
121
// Create rejected lazy promise
122
const lazyRejected = PLazy.reject(new Error("Something went wrong"));
123
```
124
125
### Promise Interface Methods
126
127
Methods that trigger lazy execution and handle promise resolution.
128
129
```javascript { .api }
130
/**
131
* Handle promise fulfillment and rejection, triggers lazy execution
132
* @param onFulfilled - Function to handle fulfilled value
133
* @param onRejected - Function to handle rejection
134
* @returns Standard Promise (not PLazy)
135
*/
136
then(onFulfilled?: Function, onRejected?: Function): Promise;
137
138
/**
139
* Handle promise rejection, triggers lazy execution
140
* @param onRejected - Function to handle rejection
141
* @returns Standard Promise (not PLazy)
142
*/
143
catch(onRejected: Function): Promise;
144
145
/**
146
* Execute cleanup logic regardless of outcome, triggers lazy execution
147
* @param onFinally - Function to execute after resolution/rejection
148
* @returns Standard Promise (not PLazy)
149
*/
150
finally(onFinally: Function): Promise;
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
const lazyPromise = new PLazy(resolve => {
157
resolve("result");
158
});
159
160
// These all trigger execution:
161
lazyPromise.then(result => console.log(result));
162
lazyPromise.catch(error => console.error(error));
163
lazyPromise.finally(() => console.log("cleanup"));
164
165
// Await also triggers execution
166
const result = await lazyPromise;
167
```
168
169
## Error Handling
170
171
P-Lazy handles errors the same way as standard Promises:
172
173
```javascript
174
const lazyPromise = new PLazy((resolve, reject) => {
175
if (Math.random() > 0.5) {
176
resolve("success");
177
} else {
178
reject(new Error("random failure"));
179
}
180
});
181
182
try {
183
const result = await lazyPromise;
184
console.log("Success:", result);
185
} catch (error) {
186
console.error("Failed:", error.message);
187
}
188
```
189
190
## Types
191
192
```javascript { .api }
193
/**
194
* Lazy Promise class that extends native Promise
195
* @template ValueType - The type of value the promise resolves to
196
*/
197
class PLazy<ValueType> extends Promise<ValueType> {
198
constructor(executor: (resolve: (value: ValueType) => void, reject: (reason: any) => void) => void);
199
static from<T>(function_: () => T | PromiseLike<T>): PLazy<T>;
200
static resolve<T>(value: T): PLazy<T>;
201
static reject<T = never>(reason: any): PLazy<T>;
202
then<TResult1 = ValueType, TResult2 = never>(
203
onFulfilled?: (value: ValueType) => TResult1 | PromiseLike<TResult1>,
204
onRejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
205
): Promise<TResult1 | TResult2>;
206
catch<TResult = never>(onRejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<ValueType | TResult>;
207
finally(onFinally?: () => void): Promise<ValueType>;
208
}
209
```