p-destruct
Create a destructured promise, gaining direct access to its internals
When working in complex asynchronous systems, it is sometimes useful to construct a promise, but resolve it somewhere else entirely. This is a single-function package inspired by Sindre's promise modules that encapsulates this process.
Usage
import pDestruct from '@jreusch/p-destruct'
const destructured = pDestruct<string>()
console.log(destructured.state) // ==> pending
destrucutred.resolve('Hello, Sailor!')
console.log(destructured.state) // ==> fulfilled
console.log(destructured.result) // ==> { state: 'fulfilled', value: 'Hello, Sailor!' }
const result = await destructured.promise
console.log(result) // ==> Hello, Sailor!
API
pDestruct<T>()
Constructs a new promise and exposes its internals, returning an object with the following properties:
promise: Promise<T>
The underlying promise object.
resolve(result: T | PromiseLike<T>)
Fulfills the promise with the given value, or continues the promise chain.
Gives you direct access to the resolve
function passed into the promise constructor (the first argument)
reject(reason: unknown)
Rejects the promise with the given reason.
Gives you direct access to the reject
function passed into the promise constructor (the second argument)
In addition to those core properties, it also exposes additional getters that allow you to inspect the current state of the promise. Note that those cannot be destructured directly, as they will lose their reactivity.
isPending: boolean
Returns true
until the promise is either resolved or rejected.
isSettled: boolean
Returns true
after the promise is resolved or rejected.
isFulfilled: boolean
Returns true
after the promise has successfully resolved.
isRejected: boolean
Returns true
if the promise got rejected.
state: string
Combined state, either 'pending'
'fulfilled'
, or 'rejected'
result: PromiseSettledResult<T>
The result after the promise has settled.