Skip to content

Class: PromisE<T> ​

Defined in: packages/promise/src/PromisE.ts:62

An attempt to solve the problem of Promise status (pending/resolved/rejected) not being easily accessible externally.

For more example see static functions like PromisE.deferred}, PromisE.fetch}, `PromisE.timeout} etc.

Examples ​

Example 1: As a drop-in replacement for Promise class ​

javascript
import PromisE from '@superutils/promise'

const p = new PromisE((resolve, reject) => resolve('done'))
console.log(
 p.pending, // Indicates if promise has finalized (resolved/rejected)
 p.resolved, // Indicates if the promise has resolved
 p.rejected // Indicates if the promise has rejected
)

Example 2: Extend an existing Proimse instance to check status ​

javascript
import PromisE from '@superutils/promise'

const instance = new Promise((resolve) => setTimeout(() => resolve(1), 1000))
const p = new PromisE(instance)
console.log(p.pending) // true
setTimeout(() => console.log({
  pending: p.pending, // false
  rejected: p.rejected, // false
  resolved: p.resolved, // true
}), 1000)

Example 3: Create a promise to be finalized externally (an alternative to "PromisE.withResolvers()") ​

javascript
import PromisE from '@superutils/promise'

const p = new PromisE()
setTimeout(() => p.resolve(1))
p.then(console.log)

Example 4. Invoke functions catching any error and wrapping the result in a PromisE instance ​

javascript
import PromisE from '@superutils/promise'

const p = PromisE.try(() => { throw new Error('I am a naughty function' ) })
p.catch(console.error)

Extends ​

Type Parameters ​

T ​

T = unknown

Constructors ​

Constructor ​

new PromisE<T>(...args): PromisE<T>

Defined in: packages/promise/src/PromisEBase.ts:31

Create a PromisE instance as a drop-in replacement for Promise

Parameters ​

args ​

...[(resolve, reject) => void]

Returns ​

PromisE<T>

Inherited from ​

PromisEBase.constructor

Constructor ​

new PromisE<T>(promise): PromisE<T>

Defined in: packages/promise/src/PromisEBase.ts:33

Extend an existing Promise instance to check status or finalize early

Parameters ​

promise ​

Promise<T>

Returns ​

PromisE<T>

Inherited from ​

PromisEBase.constructor

Constructor ​

new PromisE<T>(value): PromisE<T>

Defined in: packages/promise/src/PromisEBase.ts:35

Create a resolved promise with value

Parameters ​

value ​

T

Returns ​

PromisE<T>

Inherited from ​

PromisEBase.constructor

Constructor ​

new PromisE<T>(value): PromisE<T>

Defined in: packages/promise/src/PromisEBase.ts:37

Create a promise to be resolved externally using .resolve() and .reject() methods

Parameters ​

value ​

undefined

Returns ​

PromisE<T>

Inherited from ​

PromisEBase.constructor

Constructor ​

new PromisE<T>(): PromisE<T>

Defined in: packages/promise/src/PromisEBase.ts:55

Create a new promise to be resolved/rejected externally.

Caution: If not resolved externally using .resolve() or .reject(). it will remain pending indefinitely. ​

Returns ​

PromisE<T>

Example ​

An alternative to "Promise.withResolvers()" ​

javascript
import PromisE from '@superutils/promise'

// create a promise that will NEVER finalize automatically
const p = new PromisE()
// resolve it manually
setTimeout(() => p.resolve(1), 1000)
p.then(console.log)

Inherited from ​

PromisEBase.constructor

Properties ​

[toStringTag] ​

readonly [toStringTag]: string

Defined in: node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts:176

Inherited from ​

PromisEBase.[toStringTag]


onEarlyFinalize ​

onEarlyFinalize: OnEarlyFinalize<T>[]

Defined in: packages/promise/src/PromisEBase.ts:10

Callbacks to be invoked whenever promise is finalized externally using resolve()/reject() methods

Inherited from ​

PromisEBase.onEarlyFinalize


onFinalize ​

onFinalize: OnFinalize<T>[]

Defined in: packages/promise/src/PromisEBase.ts:13

Callback to be invoked after promise is resolved or rejected

Inherited from ​

PromisEBase.onFinalize


reject ​

reject: (reason) => void

Defined in: packages/promise/src/PromisEBase.ts:16

Early finalize by force rejecting a pending promise

Parameters ​

reason ​

unknown

Returns ​

void

Inherited from ​

PromisEBase.reject


resolve ​

resolve: (value) => void

Defined in: packages/promise/src/PromisEBase.ts:19

Early finalize by force resolving a pending promise

Parameters ​

value ​

T | PromiseLike<T>

Returns ​

void

Inherited from ​

PromisEBase.resolve


state ​

readonly state: 0 | 1 | 2 = 0

Defined in: packages/promise/src/PromisEBase.ts:28

Get promise status code:

  • 0 = pending
  • 1 = resolved
  • 2 = rejected

Inherited from ​

PromisEBase.state


[species] ​

readonly static [species]: PromiseConstructor

Defined in: node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts:180

Inherited from ​

PromisEBase.[species]


deferred ​

static deferred: typeof deferred

Defined in: packages/promise/src/PromisE.ts:63


deferredCallback ​

static deferredCallback: <TDefault, ThisArg, Delay, CbArgs>(callback, options) => <TResult>(...args) => IPromisE<TResult>

Defined in: packages/promise/src/PromisE.ts:65

Function

PromisE.deferredCallback

Type Parameters ​

TDefault ​

TDefault = unknown

ThisArg ​

ThisArg = unknown

Delay ​

Delay = unknown

CbArgs ​

CbArgs extends unknown[] = unknown[]

Parameters ​

callback ​

(...args) => TDefault | Promise<TDefault>

options? ​

DeferredAsyncOptions<ThisArg, Delay> = {}

Returns ​

deferred/throttled function

<TResult>(...args) => IPromisE<TResult>

Example ​

Debounce/deferred event handler ​

typescript
import PromisE from '@superutils/promise'

// Input change handler
const handleChange = e => console.log(e.target.value)
// Change handler with `PromisE.deferred()`
const handleChangeDeferred = PromisE.deferredCallback(handleChange, {
  delay: 300,
  throttle: false,
})
// Simulate input change events after prespecified delays
const delays = [100, 150, 200, 550, 580, 600, 1000, 1100]
delays.forEach(timeout =>
	 setTimeout(
	   () => handleChangeDeferred({ target: { value: timeout } }),
	   timeout,
	 ),
)
// Prints:
// 200, 600, 1100

delay ​

static delay: typeof delay

Defined in: packages/promise/src/PromisE.ts:67


delayReject ​

static delayReject: <T>(duration, reason?) => IPromisE_Delay<T>

Defined in: packages/promise/src/PromisE.ts:69

Function

PromisE.delayReject

Type Parameters ​

T ​

T = never

Parameters ​

duration ​

number

reason? ​

unknown

Returns ​

IPromisE_Delay<T>

Examples ​

Create a promise that will rejectafter 3 seconds ​

javascript
import PromisE from '@superutils/promise'

const rejectPromise = PromisE.delayReject(
    3000, // duration in milliseconds
    new Error('App did not initialization on time'), // reason to reject with
)
await rejectPromise // throws error message after 3 seconds
codeThatWillNotExecute()

Prevent automated promise rejection by forcing it to resolve before timeout ​

javascript
import PromisE from '@superutils/promise'

const rejectPromise = PromisE.delayReject(
    3000,
    new Error('App did not initialization on time'),
)
let count = 0
const appReady = () => ++count >= 2 // return true on second call
const intervalId = setInterval(() => {
    if (!appReady()) return
    rejectPromise.resolve('force resolves rejectPromise and execution continues')
    clearInterval(intervalId)
}, 100)
await rejectPromise
console.log('App is now ready')

retry ​

static retry: {<T>(func, options): PromisEBase<Awaited<T>>; defaults: object; }

Defined in: packages/promise/src/PromisE.ts:71

Executes a function asynchronously and retries it on failure or until a specific condition is met.

The function will be re-executed if:

  1. The func promise rejects or the function throws an error.
  2. The optional retryIf function returns true.
  3. retry > 0

Retries will stop when the retry count is exhausted, or when func executes successfully (resolves without error) AND the retryIf (if provided) returns false.

Type Parameters ​

T ​

T

The type of the value that the func resolves to.

Parameters ​

func ​

() => ValueOrPromise<T>

The function to execute. It can be synchronous or asynchronous.

options ​

RetryOptions<T>

(optional) Configuration of the retry mechanism.

The following options' default values can be configured to be EFFECTIVE GLOBALLY.

typescript
PromisE.retry.defaults = {
    retry: 1,
    retryBackOff: 'exponential',
    retryDelay: 300,
    retryDelayJitter: true,
    retryDelayJitterMax: 100,
}

Returns ​

PromisEBase<Awaited<T>>

A promise that resolves with the result of the last successful execution of func. If all retries fail (either by throwing an error or when retryIf() returned true in every time), it resolves with the last return value of func(). Errors thrown by func are caught and handled internally, only re-thrown if no result is received after maximum retries.

Examples ​

Execute function and retry on failure ​

javascript
import { retry } from '@superutils/promise'
let count = 0
const getCount = async () => {
	if (++count < 5) throw new Error('Try again')

	return count
}

const result = await retry(
  getCount,
  { retry: 10 } // retry up to 10 times
)
// will succeed on 5th try
console.log({ result })

Execute function and retry with custom logic ​

javascript
import { retry } from '@superutils/promise'

let count = 0
const getCount = async () => ++count

const result = await retry(getCount, {
	retry: 10,
	// Keep retrying until count is >= 8
	retryIf: (result = 0, _retryCount, error) => !!error || result < 8,
})
console.log({ result })

defaults ​

defaults: object

Global default values

defaults.retry ​

retry: number = 1

defaults.retryBackOff ​

retryBackOff: "exponential" = 'exponential'

defaults.retryDelay ​

retryDelay: number = 300

defaults.retryDelayJitter ​

retryDelayJitter: true = true

defaults.retryDelayJitterMax ​

retryDelayJitterMax: number = 100


timeout ​

static timeout: typeof timeout

Defined in: packages/promise/src/PromisE.ts:73

Accessors ​

pending ​

Get Signature ​

get pending(): boolean

Defined in: packages/promise/src/PromisEBase.ts:124

Indicates if the promise is still pending/unfinalized

Returns ​

boolean

Indicates if the promise is still pending/unfinalized

Inherited from ​

PromisEBase.pending


rejected ​

Get Signature ​

get rejected(): boolean

Defined in: packages/promise/src/PromisEBase.ts:129

Indicates if the promise has been rejected

Returns ​

boolean

Indicates if the promise has been rejected

Inherited from ​

PromisEBase.rejected


resolved ​

Get Signature ​

get resolved(): boolean

Defined in: packages/promise/src/PromisEBase.ts:134

Indicates if the promise has been resolved

Returns ​

boolean

Indicates if the promise has been resolved

Inherited from ​

PromisEBase.resolved

Methods ​

catch() ​

catch<TResult>(onrejected?): Promise<T | TResult>

Defined in: node_modules/typescript/lib/lib.es5.d.ts:1564

Attaches a callback for only the rejection of the Promise.

Type Parameters ​

TResult ​

TResult = never

Parameters ​

onrejected? ​

((reason) => TResult | PromiseLike<TResult>) | null

The callback to execute when the Promise is rejected.

Returns ​

Promise<T | TResult>

A Promise for the completion of the callback.

Inherited from ​

PromisEBase.catch


finally() ​

finally(onfinally?): Promise<T>

Defined in: node_modules/typescript/lib/lib.es2018.promise.d.ts:29

Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

Parameters ​

onfinally? ​

(() => void) | null

The callback to execute when the Promise is settled (fulfilled or rejected).

Returns ​

Promise<T>

A Promise for the completion of the callback.

Inherited from ​

PromisEBase.finally


then() ​

then<TResult1, TResult2>(onfulfilled?, onrejected?): Promise<TResult1 | TResult2>

Defined in: node_modules/typescript/lib/lib.es5.d.ts:1557

Attaches callbacks for the resolution and/or rejection of the Promise.

Type Parameters ​

TResult1 ​

TResult1 = T

TResult2 ​

TResult2 = never

Parameters ​

onfulfilled? ​

((value) => TResult1 | PromiseLike<TResult1>) | null

The callback to execute when the Promise is resolved.

onrejected? ​

((reason) => TResult2 | PromiseLike<TResult2>) | null

The callback to execute when the Promise is rejected.

Returns ​

Promise<TResult1 | TResult2>

A Promise for the completion of which ever callback is executed.

Inherited from ​

PromisEBase.then


all() ​

static all<T>(values): PromisEBase<{ -readonly [P in string | number | symbol]: Awaited<T[P]> }>

Defined in: packages/promise/src/PromisEBase.ts:145

Sugar for new PromisE(Promise.all(...))

Type Parameters ​

T ​

T extends unknown[]

Parameters ​

values ​

T

Returns ​

PromisEBase<{ -readonly [P in string | number | symbol]: Awaited<T[P]> }>

Inherited from ​

PromisEBase.all


allSettled() ​

static allSettled<T>(values): PromisEBase<PromiseSettledResult<Awaited<T[number]>>[]>

Defined in: packages/promise/src/PromisEBase.ts:151

Sugar for new PromisE(Promise.allSettled(...))

Type Parameters ​

T ​

T extends unknown[]

Parameters ​

values ​

T

Returns ​

PromisEBase<PromiseSettledResult<Awaited<T[number]>>[]>

Inherited from ​

PromisEBase.allSettled


any() ​

static any<T>(values): PromisEBase<Awaited<T[number]>>

Defined in: packages/promise/src/PromisEBase.ts:157

Sugar for new PromisE(Promise.any(...))

Type Parameters ​

T ​

T extends unknown[]

Parameters ​

values ​

T

Returns ​

PromisEBase<Awaited<T[number]>>

Inherited from ​

PromisEBase.any


race() ​

static race<T>(values): PromisEBase<Awaited<T[number]>>

Defined in: packages/promise/src/PromisEBase.ts:161

Sugar for new PromisE(Promise.race(..))

Type Parameters ​

T ​

T extends unknown[]

Parameters ​

values ​

T

Returns ​

PromisEBase<Awaited<T[number]>>

Inherited from ​

PromisEBase.race


reject() ​

static reject<T>(reason): PromisEBase<T>

Defined in: packages/promise/src/PromisEBase.ts:165

Extends Promise.reject

Type Parameters ​

T ​

T = never

Parameters ​

reason ​

unknown

Returns ​

PromisEBase<T>

Inherited from ​

PromisEBase.reject


resolve() ​

static resolve<T>(value?): PromisEBase<T>

Defined in: packages/promise/src/PromisEBase.ts:174

Sugar for new PromisE(Promise.resolve(...))

Type Parameters ​

T ​

T

Parameters ​

value? ​

T | PromiseLike<T>

Returns ​

PromisEBase<T>

Inherited from ​

PromisEBase.resolve


try() ​

static try<T, U>(callbackFn, ...args): PromisEBase<Awaited<T>>

Defined in: packages/promise/src/PromisEBase.ts:178

Sugar for new PromisE(Promise.try(...))

Type Parameters ​

T ​

T

U ​

U extends unknown[] = []

Parameters ​

callbackFn ​

(...args) => T | PromiseLike<T>

args ​

...U

Returns ​

PromisEBase<Awaited<T>>

Inherited from ​

PromisEBase.try


withResolvers() ​

static withResolvers<T>(): object

Defined in: packages/promise/src/PromisEBase.ts:217

Creates a PromisE instance and returns it in an object, along with its resolve and reject functions.

NB: this function is technically no longer needed because the PromisE class already comes with the resolvers.


Type Parameters ​

T ​

T = unknown

Returns ​

object

promise ​

promise: PromisEBase<T>

reject ​

reject: (reason) => void = promise.reject

Parameters ​
reason ​

unknown

Returns ​

void

resolve ​

resolve: (value) => void = promise.resolve

Parameters ​
value ​

T | PromiseLike<T>

Returns ​

void

Examples ​

Using PromisE directly: simply provide an empty function as the executor

typescript
import PromisE from '@superutils/promise'
const promisE = new PromisE<number>(() => {})
setTimeout(() => promisE.resolve(1), 1000)
promisE.then(console.log)

Using withResolvers

typescript
import PromisE from '@superutils/promise'
const pwr = PromisE.withResolvers<number>()
setTimeout(() => pwr.resolve(1), 1000)
pwr.promise.then(console.log)

Inherited from ​

PromisEBase.withResolvers