npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

promise-logic

v2.6.5

Published

Compose promises with logic gate semantics (AND, OR, XOR, NAND, NOR, XNOR, Majority). Forget APIs, remember logic.

Readme

1. Core Philosophy

Replace API Memory with Logical Concepts
The design philosophy of promise-logic is: Developers should focus on business logic, not the details of Promise APIs.
Traditional Promise combinations (such as Promise.all, Promise.race) have naming and semantics that are not intuitive enough, especially in complex asynchronous scenarios where code readability rapidly declines.
promise-logic abstracts asynchronous combinations into logical operations like and, or, xor through the concept of Logic Gates, making code semantically clear and self-explanatory.


2. Features

  1. Logical Semantics

    • and: All tasks must succeed (equivalent to Promise.all)

    • or: At least one task succeeds (equivalent to Promise.race)

    • xor: Exactly one task succeeds (no direct equivalent in traditional Promise)

    • nand: All tasks fail

    • not: Inverts the result of a single Promise

    • majority: Most tasks succeed

  2. Zero Dependencies
    Only depends on native Promise, no additional runtime dependencies.

  3. Full Test Coverage
    All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.

  4. Clear Error Classification

    • PromiseLogicError unified error type
    • error.type distinguishes specific logical errors (e.g., 'XOR_ERROR')
  5. Timeout Control

    • maxTimer: Adds timeout functionality to any Promise operation
  6. Extended Operations

    • allFulfilled: Returns all successful results
    • allRejected: Returns all failed results
    • allSettled: Returns all results (both successful and failed)

3. Installation

npm install promise-logic

4. Quick Start

Example: Primary/Backup Service Call (XOR Scenario)

import { PromiseLogic } from 'promise-logic';

// Primary service call
const primary = fetch('https://api.main.com/data');
// Backup service call
const backup = fetch('https://api.backup.com/data');

// Execute XOR logic: exactly one success
PromiseLogic.xor([primary, backup])
  .then(result => {
    console.log('Successfully fetched data:', result);
  })
  .catch(error => {
    if (error.type === 'XOR_ERROR') {
      console.error('Both primary and backup services succeeded or failed, which does not meet XOR semantics');
    } else {
      console.error('Network error:', error);
    }
  });

Example: Majority Decision (Majority Scenario)

import { PromiseLogic } from 'promise-logic';

const services = [
  fetch('https://api.node1.com/vote'),
  fetch('https://api.node2.com/vote'),
  fetch('https://api.node3.com/vote')
];

PromiseLogic.majority(services)
  .then(results => {
    console.log('Majority of services returned success:', results);
  })
  .catch(error => {
    console.error('Majority of services failed:', error);
  });
import { PromiseLogic } from 'promise-logic/typescript';

const services = [
  fetch('https://api.node1.com/vote'),
  fetch('https://api.node2.com/vote'),
  fetch('https://api.node3.com/vote')
];

PromiseLogic.majority<Response>(services)
  .then(results => {
    console.log('Majority of services returned success:', results);
  })
  .catch(error => {
    console.error('Majority of services failed:', error);
  });

Example: Timeout Control

import { PromiseLogic } from 'promise-logic';

// Execute operation with timeout
PromiseLogic.and([
  Promise.resolve(1),
  new Promise(resolve => setTimeout(resolve, 1000)), // 1 second operation
  Promise.resolve(3)
])
.maxTimer(2000) // 2 second timeout
.then(result => {
  console.log('Operation completed within timeout:', result);
})
.catch(error => {
  console.error('Operation timed out or failed:', error.message);
});

Example: Extended Operations

import { PromiseLogic } from 'promise-logic';

const operations = [
  Promise.resolve('success1'),
  Promise.reject('error1'),
  Promise.resolve('success2'),
  Promise.reject('error2')
];

// Get all successful results
PromiseLogic.allFulfilled(operations)
  .then(results => {
    console.log('Successful results:', results); // ['success1', 'success2']
  });

// Get all failed results
PromiseLogic.allRejected(operations)
  .then(errors => {
    console.log('Failed results:', errors); // ['error1', 'error2']
  });

// Get all results (both success and failure)
PromiseLogic.allSettled(operations)
  .then(results => {
    console.log('All results:', results);
  });

Example: Custom majority threshold

import { PromiseLogic } from 'promise-logic';

const services = [
  Promise.resolve('service1'),
  Promise.resolve('service2'),
  Promise.reject('service3'),
  Promise.reject('service4')
];

// Default threshold (0.5): requires at least 3 successes
// Custom threshold (0.4): requires at least 2 successes
PromiseLogic.majority(services, { max: 0.4 })
  .then(results => {
    console.log('Custom threshold met, successful results:', results); // ['service1', 'service2']
  })
  .catch(error => {
    console.error('Custom threshold not met:', error);
  });

5. API Reference

| API | Description | | :------------ | :-------------------------------------------------------------------------- | | and | All Promises succeed, returns result array; any failure causes overall failure. | | or | At least one Promise succeeds, returns first success result; all failures cause overall failure. | | xor | Exactly one Promise succeeds, returns that result; otherwise throws XOR_ERROR. | | nand | All Promises fail, returns error array; any success causes overall failure. | | not | Inverts the result of a single Promise | | majority | More than half of Promises succeed, returns success result array; otherwise overall failure. Accepts options parameter, where max property can customize threshold (default: 0.5). | | allFulfilled | Returns all successful results as an array, ignoring failures. | | allRejected | Returns all failed results as an array, ignoring successes. | | allSettled | Returns all results (both successful and failed) as an array. | | maxTimer | Adds timeout functionality to any Promise operation (unit: milliseconds). |


6. Real-world Application Scenarios

  1. Primary/Backup Service Calls
    • Use xor to ensure exactly one service responds, avoiding duplicate processing.
  2. Distributed Decision Making
    • Use majority to implement majority consensus (e.g., distributed voting).
  3. Resource Competition
    • Use or to get the first available resource (e.g., CDN node selection).
    • Use not to check if a resource is available.
  4. Full-link Validation
    • Use and to ensure all dependent services succeed (e.g., order creation).

7. Contribution Guide

  1. Development Environment
    git clone https://github.com/haowhite/promise-logic.git
    cd promise-logic
    npm install
  2. Testing
    npm test
  3. Commit Guidelines
    • Commit messages must include prefixes like feat: (new feature), fix: (bug fix), docs: (documentation).
    • Pull Requests must include test cases.

8. Resource Links