Skip to content

DeferredValue

type: class
since: v2.9.0

A utility class that represents a value that will be available at some point in the future. It encapsulates a Promise and provides methods to resolve, reject, and reset the Promise.

This is particularly useful when you need to pass a Promise to a consumer but want to control its resolution or rejection from a different part of your code.

The deferredValueErrorScope app error scope array is exported by this utility and can be used to filter thrown AppError by scope for this specific utility.
To learn more about error handling please refer to error handling section of the getting started guide, and the AppError documentation.

Usage

Basic Usage

import { DeferredValue } from '@mustib/utils/common';
const deferred = new DeferredValue<string>();
// Somewhere in your code, you can resolve the deferred value
deferred.resolve('Hello, World!');
// In another part of your code, you can await the promise
async function consume() {
const value = await deferred.current;
console.log(value); // logs 'Hello, World!'
}
consume();

Rejection

import { DeferredValue, AppError } from '@mustib/utils/common';
const deferred = new DeferredValue<string>();
// Rejeect the promise
deferred.reject(new Error('Something went wrong'));
// Handle the rejection
async function consume() {
try {
await deferred.current;
} catch (error) {
console.error(error.message); // logs 'Something went wrong'
}
}
consume();

Definition

export class DeferredValue<T> {
constructor() { }
}

T is the generic type passed to the DeferredValue<T> on instantiation.

Properties

current readonly

The Promise that this DeferredValue encapsulates.

type: Promise<T>

resolvedValue readonly

Gets the resolved value of the DeferredValue.

type: T

isPending readonly

Gets whether the DeferredValue is pending.

type: boolean

isResolved readonly

Gets whether the DeferredValue is resolved.

type: boolean

isRejected readonly

Gets whether the DeferredValue is rejected.

type: boolean

isFulfilled readonly

Gets whether the DeferredValue is fulfilled (resolved or rejected).

type: boolean

Methods

resolve

Resolves the DeferredValue with the given value.

Definition

function resolve(v: T): void { }

Parameters

  1. v
    type v = T;
    • The value to resolve the DeferredValue with.

reject

Rejects the DeferredValue with the given reason.

Definition

function reject(reason: Error): void { }

Parameters

  1. reason
    type reason = Error;
    • The reason to reject the DeferredValue with.

reset

Resets the DeferredValue to its initial state.

Definition

function reset(): void { }

abort

Aborts the DeferredValue, rejecting it with an AppError if it is still pending.

Definition

function abort(): void { }

Types

ErrorTypes

The possible error types for AppError thrown by DeferredValue.

type: 'Invalid' | 'Abort'