Skip to content

Commit

Permalink
feat: add promiseTimeout (#223)
Browse files Browse the repository at this point in the history
  • Loading branch information
kristw authored and zhaoyongjie committed Nov 26, 2021
1 parent e6c3fad commit c0c45c2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export { default as convertKeysToCamelCase } from './utils/convertKeysToCamelCas
export { default as isDefined } from './utils/isDefined';
export { default as isRequired } from './utils/isRequired';
export { default as makeSingleton } from './utils/makeSingleton';
export { default as promiseTimeout } from './utils/promiseTimeout';

export * from './types';
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/** setTimeout that returns a promise */
export default function promiseTimeout(
/** A function to be executed after the timer expires. */
func: Function,
/** The time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, as soon as possible. */
delay?: number,
) {
return new Promise(resolve => {
setTimeout(() => {
resolve(func());
}, delay);
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { promiseTimeout } from '../../src';

describe('promiseTimeout(func, delay)', () => {
it('resolves after delay', async () => {
const result = await promiseTimeout(() => 'abc', 10);
expect(result).toEqual('abc');
});
it('uses the timer', async () => {
const result = await Promise.race([
promiseTimeout(() => 'abc', 10),
promiseTimeout(() => 'def', 20),
]);
expect(result).toEqual('abc');
});
});

0 comments on commit c0c45c2

Please sign in to comment.