lz-promise
v1.0.1
Published
Lazy evaluation for asynchronous operations
Downloads
3
Readme
lz-promise
Lazy evaluation for asynchronous operations to simplify writing efficient imperative control flow.
Inspired by lazy evaluation in languages like Haskell and Scala, except only for async operations.
Motivation
One pitfall of Promises is that they immediately execute with construction. When programming imperatively with async/await, there are often values resulting from IO calls that you only use if the code follows a particular path. It is difficult to write elegant code while minimizing these costly operations. This package solves this problem by deferring the execution of the Promise until its value is needed, and saving the value for later use, so it is never excecuted more than necessary.
Usage
const { lz } = require('lz-promise');
// creates a LazyPromise
const lazyValue = lz(() => new Promise(resolve => {
console.log('executing');
resolve();
));
// only executes when .then(), .catch(), or .finall() is called on LazyPromise
await lazyValue; // > executing
Examples
Early return
async function sendMessageToUser(message, lazyUser) {
if (message.trim().length === 0) {
throw new Error('message must have content');
}
const user = await lazyUser;
user.send(message);
// ...
}
async function main() {
const lazyUser = lz(() => api.getUser(id);
await sendMessageToUser('hello', lazyUser);
if (/* someCondition*/){
// will only make API call if we haven't already
const user = await lazyUser;
await user.update();
}
}
Conditional Control Flow
async function withLazy() {
const lazyValue1 = lz(() => costlyApiCall1());
const lazyValue2 = lz(() => costlyApiCall2());
if (x) {
// result of costlyApiCall1() is stored for next lazy usage
console.log(await lazyValue1);
}
if (y) {
// uses last result if available
console.log(await lazyValue1);
console.log(await lazyValue2);
}
if (z) {
console.log(await lazyValue2);
}
}
Array Operations
async function sendLastMessageToAllUsers(lazyLastMessage, users) {
// if users is empty, no time is wasted fetching the last message
await Promise.all(users.map(async user => user.send(await lazyMessage));
}
API
Classes
Functions
LazyPromise
Kind: global class
- LazyPromise
- new LazyPromise(executor)
- instance
- .then(onFulfilled, onRejected) ⇒ Promise
- .catch(onRejected) ⇒ Promise
- .finally(onFinally) ⇒ Promise
- static
new LazyPromise(executor)
| Param | Type | Description | | --- | --- | --- | | executor | function | Callback used to initialize the promise. This callback is passed two arguments: a resolve callback used resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error. |
lazyPromise.then(onFulfilled, onRejected) ⇒ Promise
Kind: instance method of LazyPromise
Returns: Promise - A Promise for the completion of which ever callback is executed.
| Param | Type | Description | | --- | --- | --- | | onFulfilled | function | The callback to execute when the Promise is resolved. | | onRejected | function | The callback to execute when the Promise is rejected. |
lazyPromise.catch(onRejected) ⇒ Promise
Kind: instance method of LazyPromise
Returns: Promise - A Promise for the completion of the callback.
| Param | Type | Description | | --- | --- | --- | | onRejected | function | The callback to execute when the Promise is rejected. |
lazyPromise.finally(onFinally) ⇒ Promise
Kind: instance method of LazyPromise
Returns: Promise - A Promise for the completion of the callback.
| Param | Type | Description | | --- | --- | --- | | onFinally | function | The callback to execute when the Promise is settled (fulfilled or rejected). |
LazyPromise.fromPromiseCreator(promiseCreator)
Kind: static method of LazyPromise
| Param | Type | Description | | --- | --- | --- | | promiseCreator | function | Function that the returns the Promise to be deferred until .then(), .catch(), or .finally() is called. |
LazyPromise.resolve(value) ⇒ Promise
Kind: static method of LazyPromise
Returns: Promise - A promise whose internal state matches the provided value.
| Param | Type | Description | | --- | --- | --- | | value | any | The value which is resolved |
LazyPromise.reject(reason) ⇒ LazyPromise
Kind: static method of LazyPromise
Returns: LazyPromise - A promise whose internal state matches the provided value.
| Param | Type | Description | | --- | --- | --- | | reason | any | The value which is rejected |
LazyPromise.all(values) ⇒ LazyPromise
Kind: static method of LazyPromise
Returns: LazyPromise - A new LazyPromise.
| Param | Type | Description | | --- | --- | --- | | values | Iterable | An iterator of Promises, values, or LazyPromises |
LazyPromise.race(values) ⇒ LazyPromise
Kind: static method of LazyPromise
Returns: LazyPromise - A new LazyPromise.
| Param | Type | Description | | --- | --- | --- | | values | Iterable | An iterator of Promises, values, or LazyPromises. |
lz(promiseCreator) ⇒ LazyPromise
Kind: global function
| Param | Type | Description | | --- | --- | --- | | promiseCreator | function | Function that the returns the Promise to be deferred until .then(), .catch(), or .finally() is called. |