Promise
Utilities for working with promises.
Example Usage
import { fakePromiseThatCanRandomlyThrow } from './promise';
// NOTE:
// This utility is meant to be used for testing code that must handle promise success/failure reliably.
// After testing remove the call and replace it with the code of your app.
// with then/catch
fakePromiseThatCanRandomlyThrow()
.then(() => console.log('1 seconds passed and success'))
.catch(() => console.log('1 seconds passed and failure'));
// with async/await
try {
await fakePromiseThatCanRandomlyThrow();
console.log('1 seconds passed and success');
} catch (error) {
console.log('1 seconds passed and failure');
}
Dependencies
registryhttps://shadcn-registry-ts.vercel.app/r/util-sleep.json
Auto Install
npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-promise.json
Manual Install
promise.ts
/**
* Source: http://localhost:3000
*/
import { sleep } from "./sleep";
/**
* A promise that can randomly:
* - return `true` (simulate success)
* - throw an error (simulate failure)
* Use this to test code that must handle promise success/failure reliably.
*/
export const fakePromiseThatCanRandomlyThrow = () => {
return new Promise<true>(async (resolve, reject) => {
await sleep(1000);
const mustThrow = Math.random() > 0.5;
if (!mustThrow) return resolve(true);
reject(new Error('Fake error'));
});
};
Test
promise.test.ts
import { describe, it, expect } from 'vitest';
import { repeatAsyncFnInParallel } from '../utility-framework/vitest.utils';
// import { calculateFrequenciesStats } from './math';
import { fakePromiseThatCanRandomlyThrow } from './promise';
describe('promise - fakePromiseThatCanRandomlyThrow', () => {
it('do it', async () => {
const FREQUENCIES = {
success: 0,
error: 0
};
await repeatAsyncFnInParallel(1_000, async () => {
try {
const result = await fakePromiseThatCanRandomlyThrow();
expect(result).toBe(true);
FREQUENCIES.success++;
} catch (error) {
expect(error).toBeInstanceOf(Error);
FREQUENCIES.error++;
}
});
// check frequencies
// console.log(calculateFrequenciesStats(FREQUENCIES));
expect(FREQUENCIES.success).toBeGreaterThan(0);
expect(FREQUENCIES.error).toBeGreaterThan(0);
});
});
Command Palette
Search for a command to run...