https://github.com/descriptinc/promise-or-value
JavaScript/TypeScript library for working with `Promise<T> | T` type
https://github.com/descriptinc/promise-or-value
Last synced: 8 months ago
JSON representation
JavaScript/TypeScript library for working with `Promise<T> | T` type
- Host: GitHub
- URL: https://github.com/descriptinc/promise-or-value
- Owner: descriptinc
- Created: 2020-05-26T20:29:48.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-07-18T22:18:12.000Z (almost 3 years ago)
- Last Synced: 2025-03-18T12:21:21.562Z (about 1 year ago)
- Language: TypeScript
- Homepage:
- Size: 521 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# promise-or-value
[](https://github.com/descriptinc/promise-or-value/actions)
[](https://badge.fury.io/js/promise-or-value)
[](https://codecov.io/gh/descriptinc/promise-or-value)
This module is designed around the idea of a custom TypeScript type:
```typescript
type PromiseOrValue = Promise | T;
```
The motivations for this type is because `Promise`s resolve asynchronously, even if you call `then` on an already-
resolved promise (e.g. `Promise.resolve(5).then(() => …)`).
Promises work this way by design! It avoids bugs.
But for performance-critical code where you're working with cacheable async data in a loop, it can be too slow.
## API
### `then(pov, onValue, onError)` - "fast" equivalent of `Promise.resolve(pov).then(onValue).catch(onError)`
```typescript
export function then(
value: PromiseOrValue,
onValue: (t: T, sync?: true) => PromiseOrValue,
onError: (error: any) => PromiseOrValue = throwingErrorCallback,
): PromiseOrValue;
```
Run some logic immediately on values, or later, for promises.
### `all(povs)` - "fast" equivalent of `Promise.all(povs)`
```typescript
export function all(values: PromiseOrValue[]): PromiseOrValue;
```
Returns array as-is if everything is a value, or calls `Promise.all` if there are any promises in the array
### `PromiseOrValueMapLike` - for caching promise data
```typescript
type PromiseOrValueMapLike = {
get(key: K): PromiseOrValue | undefined;
set(key: K, value: PromiseOrValue): void;
};
```
A type used by `getOrAdd`. A simple conforming cache can be made with `new Map>()`.
### `getOrAdd` - for working with `PromiseOrValueMapLike`
```typescript
export function getOrAdd(
cache: PromiseOrValueMapLike,
key: K,
compute: (key: K) => PromiseOrValue,
): PromiseOrValue;
```
If the key exists in the cache, returns it, otherwise computes it and inserts it in the cache. If the computation
returns a promise, the promise is inserted in the cache, and replaced with the literal value once it resolves.