Socket
Socket
Sign inDemoInstall

value-or-promise

Package Overview
Dependencies
0
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    value-or-promise

A thenable to streamline a possibly sync / possibly async workflow.


Version published
Weekly downloads
6.3M
increased by0.38%
Maintainers
1
Install size
29.5 kB
Created
Weekly downloads
 

Package description

What is value-or-promise?

The 'value-or-promise' npm package is designed to handle values that could either be a direct value or a promise that resolves to a value. It provides utility functions to work with such values or promises in a consistent way, without having to check the nature of the value each time.

What are value-or-promise's main functionalities?

Handling values or promises uniformly

This feature allows you to handle both direct values and promises using the same API, which simplifies the code when the nature of the value is not known in advance or can vary.

const { ValueOrPromise } = require('value-or-promise');

function getValueOrPromise(value) {
  return new ValueOrPromise(() => value)
    .then(v => v)
    .resolve();
}

// Usage with a direct value
getValueOrPromise(42).then(console.log); // 42

// Usage with a promise
getValueOrPromise(Promise.resolve(42)).then(console.log); // 42

Chaining operations

This feature allows chaining multiple operations on a value or promise, with each operation being applied as the previous one resolves. It's similar to promise chaining but works with non-promise values as well.

const { ValueOrPromise } = require('value-or-promise');

function chainOperations(value) {
  return new ValueOrPromise(() => value)
    .then(v => v * 2)
    .then(v => v + 1)
    .resolve();
}

// Usage with a direct value
chainOperations(10).then(console.log); // 21

// Usage with a promise
chainOperations(Promise.resolve(10)).then(console.log); // 21

Error handling

This feature provides a way to handle errors that may occur during the processing of a value or promise, similar to how errors are caught in promise chains.

const { ValueOrPromise } = require('value-or-promise');

function handleErrors(value) {
  return new ValueOrPromise(() => value)
    .then(v => {
      if (v < 0) throw new Error('Negative value');
      return v;
    })
    .catch(error => 'Error: ' + error.message)
    .resolve();
}

// Usage with a direct value
handleErrors(-10).then(console.log); // Error: Negative value

// Usage with a promise
handleErrors(Promise.resolve(-10)).then(console.log); // Error: Negative value

Other packages similar to value-or-promise

Readme

Source

value-or-promise

A thenable to streamline a possibly sync / possibly async workflow.

Installation

yarn add value-or-promise or npm install value-or-promise

Basic Motivation

Instead of writing:

function myFunction() {
    const valueOrPromise = getValueOrPromise();

    if (isPromise(valueOrPromise)) {
        return valueOrPromise.then(v => onValue(v));
    }
    
    return onValue(valueOrPromise);
}

...write:

function myFunction() {
    return new ValueOrPromise(getValueOrPromise)
        .then(v => onValue(v))
        .resolve();
}

When working with functions that may or may not return promises, we usually have to duplicate handlers in both the synchronous and asynchronous code paths. In the most basic scenario included above, using value-or-promise already provides some code savings, i.e. we only have to reference doSomethingWithValue once.

More Chaining

Things start to get even more beneficial when we add more sync-or-async functions to the chain.

Instead of writing:

function myFunction() {
    const valueOrPromise = getValueOrPromise();

    if (isPromise(valueOrPromise)) {
        return valueOrPromise
            .then(v => first(v))
            .then(v => second(v));
    }

    const nextValueOrPromise = first(ValueOrPromise)

    if (isPromise(nextValueOrPromise)) {
        return nextValueOrPromise.then(v => second(v));
    }
    
    return second(nextValueOrPromise);
}

...write:

function myFunction() {
    return new ValueOrPromise(getValueOrPromise)
        .then(v => first(v))
        .then(v => second(v))
        .resolve();
}

Error Handling

Even with shorter chains, value-or-promise comes in handy when managing errors.

Instead of writing:

function myFunction() {
    try {
        const valueOrPromise = getValueOrPromise();

        if (isPromise(valueOrPromise)) {
            return valueOrPromise
                .then(v => onValue(v))
                .catch(error => console.log(error));
        }
    
        const nextValueOrPromise = onValue(valueOrPromise);

        if (isPromise(nextValueOrPromise)) {
            return nextValueOrPromise
                .catch(error => console.log(error));
        }

        return nextValueOrPromise;
    } catch (error) {
        console.log(error);
    }
}

...write:

function myFunction() {
    return new ValueOrPromise(getValueOrPromise)
        .then(v => onValue(v))
        .catch(error => console.log(error))
        .resolve();
}

Alternatives

A simpler way of streamlining the above is to always return a promise.

Instead of writing:

function myFunction() {
    const valueOrPromise = getValueOrPromise();

    if (isPromise(valueOrPromise)) {
        return valueOrPromise.then(v => onValue(v));
    }
    
    return onValue(valueOrPromise);
}

...or writing:

function myFunction() {
    return new ValueOrPromise(getValueOrPromise)
        .then(v => onValue(v))
        .resolve();
}

...we could write:

function myFunction() {
    return Promise.resolve(getValueOrPromise)
        .then(v => onValue(v));
}

...but then we would always have to return a promise! If we are trying to avoid the event loop when possible, this will not suffice.

ValueOrPromise.all(...)?

We can use ValueOrPromise.all(...) analogous to Promise.all(...) to create a new ValueOrPromise object that will either resolve to an array of values, if none of the passed ValueOrPromise objects contain underlying promises, or to a new promise, if one or more of the ValueOrPromise objects contain an underlying promise, where the new promise will resolve when all of the potential promises have resolved.

For example:

function myFunction() {
    const first = new ValueOrPromise(getFirst);
    const second = new ValueOrPromise(getSecond);
    return ValueOrPromise.all([first, second]).then(
        all => onAll(all)
    ).resolve();
}

myFunction with return a value if and only if getFirst and getSecond both return values. If either returns a promise, myFunction will return a promise. If both getFirst and getSecond return promises, the new promise returned by myFunction will resolve only after both promises resolve, just like with Promise.all.

Inspiration

The value-to-promise concept is by Ivan Goncharov.

Implementation errors are my own.

FAQs

Last updated on 03 Jan 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc