Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created April 3, 2022 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/274c229d4c2339a8e233a64ffdc6df55 to your computer and use it in GitHub Desktop.
Save renatoargh/274c229d4c2339a8e233a64ffdc6df55 to your computer and use it in GitHub Desktop.
const sleep = async (timeout: number = 1000) =>
// tslint:disable-next-line:no-string-based-set-timeout
new Promise((res) => setTimeout(res, timeout));
/**
* A test-only utility that executes a function until a given condition is met.
* Useful to wait for asynchronous operations to complete on integration tests.
* If the condition is never met (`condition` never returns `true`) then tests will eventually timeout accordin to
* the test framework timeout settings.
* @param task Asynchronous function that will be repeatedly executed until the the desired `condition` is met.
* @param condition Function that evalutes the results of `task`. Return `true` to indicate that the condition is met.
* @param retryInterval Interval in milliseconds to wait between the next execution of `task`. Defaults to 100ms.
* @return A promise that resolves with the last results returned by `task` when the condition is met.
*/
export const waitFor = async <T>(
task: () => Promise<T>,
condition: (taskResults: T) => boolean,
retryInterval: number = 100,
): Promise<T> => {
const results = await task();
const isReady = condition(results);
if (isReady) {
return results;
}
await sleep(retryInterval);
return waitFor(task, condition);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment