promise-logic
v2.6.5
Published
Compose promises with logic gate semantics (AND, OR, XOR, NAND, NOR, XNOR, Majority). Forget APIs, remember logic.
Maintainers
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
Logical Semantics
and: All tasks must succeed (equivalent toPromise.all)or: At least one task succeeds (equivalent toPromise.race)xor: Exactly one task succeeds (no direct equivalent in traditional Promise)nand: All tasks failnot: Inverts the result of a single Promisemajority: Most tasks succeed
Zero Dependencies
Only depends on native Promise, no additional runtime dependencies.Full Test Coverage
All logic gates have undergone rigorous unit testing to ensure behavior meets expectations.Clear Error Classification
PromiseLogicErrorunified error typeerror.typedistinguishes specific logical errors (e.g.,'XOR_ERROR')
Timeout Control
maxTimer: Adds timeout functionality to any Promise operation
Extended Operations
allFulfilled: Returns all successful resultsallRejected: Returns all failed resultsallSettled: Returns all results (both successful and failed)
3. Installation
npm install promise-logic4. 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
- Primary/Backup Service Calls
- Use
xorto ensure exactly one service responds, avoiding duplicate processing.
- Use
- Distributed Decision Making
- Use
majorityto implement majority consensus (e.g., distributed voting).
- Use
- Resource Competition
- Use
orto get the first available resource (e.g., CDN node selection). - Use
notto check if a resource is available.
- Use
- Full-link Validation
- Use
andto ensure all dependent services succeed (e.g., order creation).
- Use
7. Contribution Guide
- Development Environment
git clone https://github.com/haowhite/promise-logic.git cd promise-logic npm install - Testing
npm test - Commit Guidelines
- Commit messages must include prefixes like
feat:(new feature),fix:(bug fix),docs:(documentation). - Pull Requests must include test cases.
- Commit messages must include prefixes like
8. Resource Links
- GitHub Repository:https://github.com/xier123456/promise-logic
- npm Package:https://www.npmjs.com/package/promise-logic
- Issue Tracking:GitHub Issues
