lz-promise
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.1 • Public • Published

    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

    LazyPromise

    Functions

    lz(promiseCreator)LazyPromise

    Alias for LazyPromise.fromPromiseCreator that creates a new LazyPromise from a function that returns a Promise.

    LazyPromise

    Kind: global class

    new LazyPromise(executor)

    Creates a new LazyPromise with the standard Promise constructor, except that executor is deferred until .then(), .catch(), or .finally() is called.

    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

    Calls the executor if it has not been executed. Attaches callbacks for the resolution and/or rejection of the resulting 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

    Calls the executor if it has not been executed. Attaches a callback for only the rejection of the resulting 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

    Calls the executor if it has not been executed. Attaches a callback that is invoked when the resulting Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

    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)

    Creates a new LazyPromise from a function that returns a Promise.

    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

    Creates a new resolved LazyPromise for the provided value. Equivalent to Promise.resolve() because value is already executed

    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

    Creates a new rejected LazyPromise for the provided value. Equivalent to Promise.reject() because value is already executed

    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

    Creates a LazyPromise that, when .then(), .catch(), or .finally() is called, is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.

    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

    Creates a LazyPromise that, when .then(), .catch(), or .finally() is called, is resolved or rejected when any of the provided Promises are resolved or rejected that Promise's value.

    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

    Alias for LazyPromise.fromPromiseCreator that creates a new LazyPromise from a function that returns a Promise.

    Kind: global function

    Param Type Description
    promiseCreator function

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

    Install

    npm i lz-promise

    DownloadsWeekly Downloads

    41

    Version

    1.0.1

    License

    MIT

    Unpacked Size

    40.1 kB

    Total Files

    12

    Last publish

    Collaborators

    • wmsmacdonald