-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}); | ||
} | ||
} |