Skip to content

Commit

Permalink
Merge 858747d into 89d714e
Browse files Browse the repository at this point in the history
  • Loading branch information
nhardy committed Apr 18, 2023
2 parents 89d714e + 858747d commit 777ddb3
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/kerosene/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ Returns the provided `value` rounded to the number of significant `figures` prov

## Promise

### `Deferred`

Deferred is a class that allows a Promise to be created in advance of the code that will `resolve`/`reject` it.

### `mapSeries(items, iteratee)`

Maps over `items` with a promise-returning `iteratee` in series.
Expand Down
1 change: 1 addition & 0 deletions packages/kerosene/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export { default as toDegrees } from "./math/toDegrees";
export { default as toRadians } from "./math/toRadians";
export { default as toSignificantFigures } from "./math/toSignificantFigures";

export { default as Deferred } from "./promise/Deferred";
export { default as mapSeries } from "./promise/mapSeries";

export * from "./string";
Expand Down
20 changes: 20 additions & 0 deletions packages/kerosene/src/promise/Deferred.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import timeout from "../function/timeout";
import Deferred from "./Deferred";

describe("Deferred", () => {
it("should allow a Promise to be created and resolved", async () => {
const deferred = new Deferred<boolean>();
deferred.resolve(true);

await expect(deferred.promise).resolves.toBe(true);
});

it("should allow a Promise to be created and reject", async () => {
const deferred = new Deferred();
const error = new Error("an error");
// Promise must be rejected _after_ a catch handler has been attached or we will see UnhandledPromiseRejection from Node
timeout(0).then(() => deferred.reject(error));

await expect(deferred.promise).rejects.toBe(error);
});
});
19 changes: 19 additions & 0 deletions packages/kerosene/src/promise/Deferred.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { Mutable } from "../types";

/**
* Deferred is a class that allows a Promise to be created in advance of the code that will `resolve`/`reject` it.
*/
export default class Deferred<T> {
public readonly promise: Promise<T>;

public readonly resolve!: (value: T) => void;

public readonly reject!: (reason?: unknown) => void;

constructor() {
this.promise = new Promise<T>((resolve, reject) => {
(this as Mutable<typeof this>).resolve = resolve;
(this as Mutable<typeof this>).reject = reject;
});
}
}

0 comments on commit 777ddb3

Please sign in to comment.