logo

DeferredPromise

The DeferredPromise class is built on top of the native Promise class. It provides a way to resolve or reject a promise from the outside.

Properties

  • instance (Promise<T>): The native promise instance.
  • reason (any): The reason for the rejection of the promise.
  • state (PromiseState): The state of the promise, can be pending, fulfilled, or rejected.
  • value (T): The value of the resolved promise.

Getters

  • isFulfilled: Checks if the promise is fulfilled. It returns true if the state of the promise is fulfilled, otherwise it returns false.
  • isPending: Checks if the promise is pending. It returns true if the state of the promise is pending, otherwise it returns false.
  • isRejected: Checks if the promise is rejected. It returns true if the state of the promise is rejected, otherwise it returns false.
  • isResolved: Checks if the promise is resolved. It returns true if the promise is fulfilled, otherwise it returns false.

Resolve the Promise

The resolve method is used to signal that the DeferredPromise has completed successfully and to provide the resulting value.

import { DeferredPromise } from '@aracna/core';

(async () => {
  let promise;

  promise = new DeferredPromise();
  console.log('promise created', Date.now());

  setTimeout(() => promise.resolve(), 1000);

  await promise.instance;
  console.log('promise resolved', Date.now());
})();

Reject the Promise

The reject method is used to signal that the DeferredPromise has been rejected and to provide the reason for the rejection.

import { DeferredPromise } from '@aracna/core';

(async () => {
  let promise;

  promise = new DeferredPromise();
  console.log('promise created', Date.now());

  setTimeout(() => promise.reject(), 1000);

  try {
    await promise.instance;
  } catch (error) {
    console.log('promise rejected', error);
  }
})();