Create a lazy promise that defers execution until it's awaited or when .then(), .catch(), or .finally() is called
npx @tessl/cli install tessl/npm-p-lazy@5.0.0P-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.
npm install p-lazyimport PLazy from "p-lazy";For CommonJS:
const PLazy = require("p-lazy");import PLazy from "p-lazy";
// Create a lazy promise that won't execute until needed
const lazyPromise = new PLazy(resolve => {
console.log("This expensive operation only runs when the promise is used");
someHeavyOperation(resolve);
});
// The executor hasn't run yet
console.log("Promise created, but executor not called");
// Now the executor runs
const result = await lazyPromise;
console.log(result);P-Lazy extends the native Promise class while implementing lazy evaluation:
.then(), .catch(), .finally(), or awaitCreates a new lazy promise with deferred execution.
/**
* Create a lazy promise that defers execution until it's awaited or when
* .then(), .catch(), or .finally() is called
* @param executor - Function with signature (resolve, reject) => void
*/
constructor(executor: (resolve: Function, reject: Function) => void);Usage Example:
const lazyPromise = new PLazy((resolve, reject) => {
setTimeout(() => {
resolve("Heavy computation result");
}, 1000);
});
// Executor hasn't run yet
await someOtherWork();
// Now executor runs and waits 1 second
const result = await lazyPromise;Factory methods for creating lazy promises from various sources.
/**
* Create a PLazy promise from a promise-returning or async function
* @param function_ - Function returning a value or Promise
* @returns PLazy promise that will execute the function when accessed
*/
static from(function_: () => any): PLazy;
/**
* Create a PLazy promise that is resolved with the given value
* @param value - Value to resolve with
* @returns PLazy promise resolved with the value
*/
static resolve(value: any): PLazy;
/**
* Create a PLazy promise that is rejected with the given reason
* @param error - Error or reason for rejection
* @returns PLazy promise rejected with the error
*/
static reject(error: any): PLazy;Usage Examples:
// Create from function
const lazyFromFunc = PLazy.from(async () => {
const data = await fetchExpensiveData();
return processData(data);
});
// Create resolved lazy promise
const lazyResolved = PLazy.resolve("immediate value");
// Create rejected lazy promise
const lazyRejected = PLazy.reject(new Error("Something went wrong"));Methods that trigger lazy execution and handle promise resolution.
/**
* Handle promise fulfillment and rejection, triggers lazy execution
* @param onFulfilled - Function to handle fulfilled value
* @param onRejected - Function to handle rejection
* @returns Standard Promise (not PLazy)
*/
then(onFulfilled?: Function, onRejected?: Function): Promise;
/**
* Handle promise rejection, triggers lazy execution
* @param onRejected - Function to handle rejection
* @returns Standard Promise (not PLazy)
*/
catch(onRejected: Function): Promise;
/**
* Execute cleanup logic regardless of outcome, triggers lazy execution
* @param onFinally - Function to execute after resolution/rejection
* @returns Standard Promise (not PLazy)
*/
finally(onFinally: Function): Promise;Usage Examples:
const lazyPromise = new PLazy(resolve => {
resolve("result");
});
// These all trigger execution:
lazyPromise.then(result => console.log(result));
lazyPromise.catch(error => console.error(error));
lazyPromise.finally(() => console.log("cleanup"));
// Await also triggers execution
const result = await lazyPromise;P-Lazy handles errors the same way as standard Promises:
const lazyPromise = new PLazy((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("success");
} else {
reject(new Error("random failure"));
}
});
try {
const result = await lazyPromise;
console.log("Success:", result);
} catch (error) {
console.error("Failed:", error.message);
}/**
* Lazy Promise class that extends native Promise
* @template ValueType - The type of value the promise resolves to
*/
class PLazy<ValueType> extends Promise<ValueType> {
constructor(executor: (resolve: (value: ValueType) => void, reject: (reason: any) => void) => void);
static from<T>(function_: () => T | PromiseLike<T>): PLazy<T>;
static resolve<T>(value: T): PLazy<T>;
static reject<T = never>(reason: any): PLazy<T>;
then<TResult1 = ValueType, TResult2 = never>(
onFulfilled?: (value: ValueType) => TResult1 | PromiseLike<TResult1>,
onRejected?: (reason: any) => TResult2 | PromiseLike<TResult2>
): Promise<TResult1 | TResult2>;
catch<TResult = never>(onRejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<ValueType | TResult>;
finally(onFinally?: () => void): Promise<ValueType>;
}