sindresorhus/p-lazy

Create a lazy promise that defers execution until it's awaited or when .then() or .catch() is called

285

stars

21

commits

JavaScript

primary language

Oct 28, 2024

updated

README

p-lazy

Create a lazy promise that defers execution until it's awaited or when .then(), or .catch(), or .finally() is called

Useful if you're doing some heavy operations and would like to only do it when the promise is actually used.

Install

npm install p-lazy

Usage

import PLazy from 'p-lazy';

const lazyPromise = new PLazy(resolve => {
	someHeavyOperation(resolve);
});

// `someHeavyOperation` is not yet called

await doSomethingFun;

// `someHeavyOperation` is called
console.log(await lazyPromise);

API

new PLazy(executor)

Same as the Promise constructor. PLazy is a subclass of Promise.

PLazy.from(fn)

Create a PLazy promise from a promise-returning or async function.

PLazy.resolve(value)

Create a PLazy promise that is resolved with the given value, or the promise passed as value.

PLazy.reject(reason)

Create a PLazy promise that is rejected with the given reason.

Contributors

sindresorhus

16 commits

BendingBender

2 commits

lmammino

1 commits

Richienb

1 commits

sindresorhus/p-lazy

Create a lazy promise that defers execution until it's awaited or when .then() or .catch() is called

285

stars

21

commits

JavaScript

primary language

Oct 28, 2024

updated

README

p-lazy

Create a lazy promise that defers execution until it's awaited or when .then(), or .catch(), or .finally() is called

Useful if you're doing some heavy operations and would like to only do it when the promise is actually used.

Install

npm install p-lazy

Usage

import PLazy from 'p-lazy';

const lazyPromise = new PLazy(resolve => {
	someHeavyOperation(resolve);
});

// `someHeavyOperation` is not yet called

await doSomethingFun;

// `someHeavyOperation` is called
console.log(await lazyPromise);

API

new PLazy(executor)

Same as the Promise constructor. PLazy is a subclass of Promise.

PLazy.from(fn)

Create a PLazy promise from a promise-returning or async function.

PLazy.resolve(value)

Create a PLazy promise that is resolved with the given value, or the promise passed as value.

PLazy.reject(reason)

Create a PLazy promise that is rejected with the given reason.

Contributors

sindresorhus

16 commits

BendingBender

2 commits

lmammino

1 commits

Richienb

1 commits

Languages

JavaScript

88.0%

TypeScript

12.0%