|
| 1 | +# promise-or-value |
| 2 | + |
| 3 | +[](https://github.com/descriptinc/promise-or-value/actions) |
| 4 | +[](https://badge.fury.io/js/promise-or-value) |
| 5 | +[](https://codecov.io/gh/descriptinc/promise-or-value) |
| 6 | + |
| 7 | +This module is designed around the idea of a custom TypeScript type: |
| 8 | + |
| 9 | +```typescript |
| 10 | +type PromiseOrValue<T> = Promise<T> | T; |
| 11 | +``` |
| 12 | + |
| 13 | +The motivations for this type is because `Promise`s resolve asynchronously, even if you call `then` on an already- |
| 14 | +resolved promise (e.g. `Promise.resolve(5).then(() => …)`). |
| 15 | + |
| 16 | +Promises work this way by design! It avoids bugs. |
| 17 | + |
| 18 | +But for performance-critical code where you're working with cacheable async data in a loop, it can be too slow. |
| 19 | + |
| 20 | +## API |
| 21 | + |
| 22 | +### `then(pov, onValue, onError)` - "fast" equivalent of `Promise.resolve(pov).then(onValue).catch(onError)` |
| 23 | + |
| 24 | +```typescript |
| 25 | +export function then<T, V>( |
| 26 | + value: PromiseOrValue<T>, |
| 27 | + onValue: (t: T, sync?: true) => PromiseOrValue<V>, |
| 28 | + onError: (error: any) => PromiseOrValue<V> = throwingErrorCallback, |
| 29 | +): PromiseOrValue<V>; |
| 30 | +``` |
| 31 | + |
| 32 | +Run some logic immediately on values, or later, for promises. |
| 33 | + |
| 34 | +### `all(povs)` - "fast" equivalent of `Promise.all(povs)` |
| 35 | + |
| 36 | +```typescript |
| 37 | +export function all<T>(values: PromiseOrValue<T>[]): PromiseOrValue<T[]>; |
| 38 | +``` |
| 39 | + |
| 40 | +Returns array as-is if everything is a value, or calls `Promise.all` if there are any promises in the array |
| 41 | + |
| 42 | +### `PromiseOrValueMapLike` - for caching promise data |
| 43 | + |
| 44 | +```typescript |
| 45 | +type PromiseOrValueMapLike<K, V> = { |
| 46 | + get(key: K): PromiseOrValue<V> | undefined; |
| 47 | + set(key: K, value: PromiseOrValue<V>): void; |
| 48 | +}; |
| 49 | +``` |
| 50 | + |
| 51 | +A type used by `getOrAdd`. A simple conforming cache can be made with `new Map<K, PromiseOrValue<V>>()`. |
| 52 | + |
| 53 | +### `getOrAdd` - for working with `PromiseOrValueMapLike` |
| 54 | + |
| 55 | +```typescript |
| 56 | +export function getOrAdd<K, V>( |
| 57 | + cache: PromiseOrValueMapLike<K, V>, |
| 58 | + key: K, |
| 59 | + compute: (key: K) => PromiseOrValue<V>, |
| 60 | +): PromiseOrValue<V>; |
| 61 | +``` |
| 62 | + |
| 63 | +If the key exists in the cache, returns it, otherwise computes it and inserts it in the cache. If the computation |
| 64 | +returns a promise, the promise is inserted in the cache, and replaced with the literal value once it resolves. |
0 commit comments