Skip to content

Commit

Permalink
feat: Add createDeferredPromise (#164)
Browse files Browse the repository at this point in the history
* feat: Add `createDeferredPromise`

A new function has been added for creating a deferred Promise. Deferred
Promises can be useful for tracking async task, e.g. to prevent async
tasks from overlapping, or to queue up async tasks. We use this pattern
in multiple places in core and the extension.

* Add type parameter for Promise result

This allows creating deferred Promises that return values
  • Loading branch information
Gudahtt authored Jan 11, 2024
1 parent 425d3d5 commit edcf2de
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe('index', () => {
"createBigInt",
"createBytes",
"createDataView",
"createDeferredPromise",
"createHex",
"createModuleLogger",
"createNumber",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export * from './logging';
export * from './misc';
export * from './number';
export * from './opaque';
export * from './promise';
export * from './time';
export * from './transaction-types';
export * from './versions';
1 change: 1 addition & 0 deletions src/node.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe('node', () => {
"createBigInt",
"createBytes",
"createDataView",
"createDeferredPromise",
"createHex",
"createModuleLogger",
"createNumber",
Expand Down
57 changes: 57 additions & 0 deletions src/promise.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { createDeferredPromise } from './promise';

describe('Promise utilities', () => {
describe('createDeferredPromise', () => {
it('creates a deferred promise that resolves when resolve is called', async () => {
const { promise, resolve } = createDeferredPromise();

resolve();

expect(await promise).toBeUndefined();
});

it('creates a deferred promise that returns a value', async () => {
const { promise, resolve } = createDeferredPromise<number>();

resolve(10);

expect(await promise).toBe(10);
});

it('creates a deferred promise that rejects when reject is called', async () => {
const { promise, reject } = createDeferredPromise();
const mockError = new Error('test error');

reject(mockError);

await expect(promise).rejects.toThrow('test error');
});

it('ignores subsequent calls to reject or resolve', async () => {
const { promise, reject, resolve } = createDeferredPromise();
resolve();
await promise;

expect(() => reject(new Error('test error'))).not.toThrow();
expect(() => resolve()).not.toThrow();
});

describe('when suppressUnhandledRejection is set', () => {
it('does not trigger an unhandled rejection event when the rejection is unhandled', async () => {
const { reject } = createDeferredPromise({
suppressUnhandledRejection: true,
});
const mockError = new Error('test error');
reject(mockError);

// Wait for unhandled rejection error to be triggered
await new Promise((resolve) => {
setTimeout(resolve, 0);
});

// If the test reaches here, it has succeeded
expect(true).toBe(true);
});
});
});
});
58 changes: 58 additions & 0 deletions src/promise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* A deferred Promise.
*
* A deferred Promise is one that can be resolved or rejected independently of
* the Promise construction.
* @template Result - The result type of the Promise.
*/
export type DeferredPromise<Result = void> = {
/**
* The Promise that has been deferred.
*/
promise: Promise<Result>;
/**
* A function that resolves the Promise.
*/
resolve: (result: Result) => void;
/**
* A function that rejects the Promise.
*/
reject: (error: unknown) => void;
};

/**
* Create a defered Promise.
*
* @param args - The arguments.
* @param args.suppressUnhandledRejection - This option adds an empty error handler
* to the Promise to suppress the UnhandledPromiseRejection error. This can be
* useful if the deferred Promise is sometimes intentionally not used.
* @returns A deferred Promise.
* @template Result - The result type of the Promise.
*/
export function createDeferredPromise<Result = void>({
suppressUnhandledRejection = false,
}: {
suppressUnhandledRejection?: boolean;
} = {}): DeferredPromise<Result> {
let resolve: DeferredPromise<Result>['resolve'];
let reject: DeferredPromise<Result>['reject'];
const promise = new Promise<Result>(
(
innerResolve: DeferredPromise<Result>['resolve'],
innerReject: DeferredPromise<Result>['reject'],
) => {
resolve = innerResolve;
reject = innerReject;
},
);

if (suppressUnhandledRejection) {
promise.catch((_error) => {
// This handler is used to suppress the UnhandledPromiseRejection error
});
}

// @ts-expect-error We know that these are assigned, but TypeScript doesn't
return { promise, resolve, reject };
}

0 comments on commit edcf2de

Please sign in to comment.