Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Commit

Permalink
feat: Add setTimeout.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenh committed Feb 10, 2022
1 parent 32b2eb1 commit ed70403
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@ export type AllowAsyncOpts = { allowAsync?: boolean };
// Guess about whether we're running in tests or production
const inTests = "beforeEach" in global;

/** A utility class for putting a promise that is explicitly resolved into the async queue. */
/** A utility creating an async-queue-aware promise that is explicitly resolved. */
export class Deferred {
resolve: () => void;
promise: Promise<unknown>;
constructor() {
this.promise = new Promise((resolve) => (this.resolve = () => resolve(undefined)));

constructor(description: string) {
addToAsyncQueue(
description,
new Promise((resolve) => {
this.resolve = () => resolve(undefined);
}),
);
}
}

Expand Down Expand Up @@ -87,3 +92,16 @@ export function checkUnexpectedAsync(opts: AllowAsyncOpts = {}): void {
}
}
}

/**
* Provides a `setTimeout` that is automatically integrated with the async queue.
*
* This is safe to use in production code w/o worrying to mock it out for tests.
*/
export function setTimeout(callback: () => void, ms?: number) {
const deferred = new Deferred("setTimeout");
return global.setTimeout(() => {
callback();
deferred.resolve();
}, ms);
}

0 comments on commit ed70403

Please sign in to comment.