1.0.1 • Published 6 years ago

lz-promise v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

lz-promise

npm Build Status Coverage Status

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

new LazyPromise(executor)

ParamTypeDescription
executorfunctionCallback 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.

ParamTypeDescription
onFulfilledfunctionThe callback to execute when the Promise is resolved.
onRejectedfunctionThe 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.

ParamTypeDescription
onRejectedfunctionThe 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.

ParamTypeDescription
onFinallyfunctionThe callback to execute when the Promise is settled (fulfilled or rejected).

LazyPromise.fromPromiseCreator(promiseCreator)

Kind: static method of LazyPromise

ParamTypeDescription
promiseCreatorfunctionFunction 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.

ParamTypeDescription
valueanyThe value which is resolved

LazyPromise.reject(reason) ⇒ LazyPromise

Kind: static method of LazyPromise
Returns: LazyPromise - A promise whose internal state matches the provided value.

ParamTypeDescription
reasonanyThe value which is rejected

LazyPromise.all(values) ⇒ LazyPromise

Kind: static method of LazyPromise
Returns: LazyPromise - A new LazyPromise.

ParamTypeDescription
valuesIterableAn iterator of Promises, values, or LazyPromises

LazyPromise.race(values) ⇒ LazyPromise

Kind: static method of LazyPromise
Returns: LazyPromise - A new LazyPromise.

ParamTypeDescription
valuesIterableAn iterator of Promises, values, or LazyPromises.

lz(promiseCreator) ⇒ LazyPromise

Kind: global function

ParamTypeDescription
promiseCreatorfunctionFunction that the returns the Promise to be deferred until .then(), .catch(), or .finally() is called.