-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add timeout
function
#250
Open
MarlonPassos-git
wants to merge
4
commits into
radashi-org:main
Choose a base branch
from
MarlonPassos-git:feature/add-timeout-promise-function
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import * as _ from 'radashi' | ||
|
||
describe('timeout', () => { | ||
bench('with default error message', async () => { | ||
try { | ||
await _.timeout(0) | ||
} catch (_) {} | ||
}) | ||
|
||
bench('with custom error message', async () => { | ||
try { | ||
await _.timeout(0, 'Optional message') | ||
} catch (_) {} | ||
}) | ||
|
||
bench('with custom error function', async () => { | ||
try { | ||
await _.timeout(0, () => new Error('Custom error')) | ||
} catch (_) {} | ||
}) | ||
}) |
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,37 @@ | ||
--- | ||
title: timeout | ||
description: Asynchronously rejects after a specified amount of time. | ||
--- | ||
|
||
### Usage | ||
|
||
The `_.timeout` function creates a promise that will reject after a given number of milliseconds. You can provide a custom error message or a function that returns an error to be thrown upon rejection. | ||
|
||
```ts | ||
import * as _ from 'radashi' | ||
|
||
// Rejects after 1 second with the default "timeout" error message | ||
await _.timeout(1000) | ||
|
||
// Rejects after 1 second with a custom error message | ||
await _.timeout(1000, 'Custom timeout message') | ||
|
||
// Rejects after 1 second with a custom error object | ||
await _.timeout(1000, () => new Error('Custom error')) | ||
``` | ||
|
||
### Example with `Promise.race` | ||
|
||
One of the most useful ways to use `_.timeout` with `Promise.race` to set a timeout for an asynchronous operation. | ||
|
||
```ts | ||
import * as _ from 'radashi' | ||
|
||
const someAsyncTask = async () => { | ||
await _.sleep(10_000) | ||
return 'Task completed' | ||
} | ||
|
||
// Race between the async task and a timeout of 1 second | ||
await Promise.race([someAsyncTask(), _.timeout(1000, 'Task took too long')]) | ||
``` |
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,48 @@ | ||
import { isString } from 'radashi' | ||
|
||
declare const setTimeout: (fn: () => void, ms: number) => unknown | ||
|
||
/** | ||
* Creates a promise that will reject after a specified amount of time. | ||
* You can provide a custom error message or a function that returns an error. | ||
* | ||
* @see https://radashi.js.org/reference/async/timeout | ||
* | ||
* @example | ||
* ```ts | ||
* // Reject after 1000 milliseconds with default message "timeout" | ||
* await timeout(1000) | ||
* | ||
* // Reject after 1000 milliseconds with a custom message | ||
* await timeout(1000, "Optional message") | ||
* | ||
* // Reject after 1000 milliseconds with a custom error | ||
* await timeout(1000, () => new Error("Custom error")) | ||
* | ||
* // Example usage with Promise.race to set a timeout for an asynchronous task | ||
* await Promise.race([ | ||
* someAsyncTask(), | ||
* timeout(1000, "Optional message"), | ||
* ]) | ||
* ``` | ||
*/ | ||
|
||
export function timeout<E extends Error>( | ||
milliseconds: number, | ||
/** | ||
* The error message to reject with. | ||
* | ||
* @default "timeout" | ||
*/ | ||
error: string | (() => E) = 'timeout', | ||
): Promise<void> { | ||
return new Promise((_, rej) => | ||
setTimeout(() => { | ||
if (isString(error)) { | ||
rej(new Error(error)) | ||
} else { | ||
rej(error()) | ||
} | ||
}, milliseconds), | ||
) | ||
} |
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,56 @@ | ||
import * as _ from 'radashi' | ||
|
||
describe('timeout', () => { | ||
beforeEach(() => { | ||
vi.useFakeTimers() | ||
}) | ||
|
||
test('rejects after a specified number of milliseconds', async () => { | ||
const promise = _.timeout(10) | ||
|
||
vi.advanceTimersToNextTimerAsync() | ||
|
||
await expect(promise).rejects.toThrow('timeout') | ||
}) | ||
|
||
test('rejects with a custom error message', async () => { | ||
const promise = _.timeout(10, 'custom error message') | ||
|
||
vi.advanceTimersToNextTimerAsync() | ||
|
||
await expect(promise).rejects.toThrow('custom error message') | ||
}) | ||
|
||
test('rejects with a custom error function', async () => { | ||
class CustomError extends Error { | ||
constructor() { | ||
super('custom error function') | ||
} | ||
} | ||
|
||
const promise = _.timeout(10, () => new CustomError()) | ||
|
||
vi.advanceTimersToNextTimerAsync() | ||
|
||
await expect(promise).rejects.toThrow(CustomError) | ||
await expect(promise).rejects.toThrow('custom error function') | ||
}) | ||
|
||
describe('with Promise.race', () => { | ||
test('resolves correctly when sleep finishes before timeout', async () => { | ||
const promise = Promise.race([_.sleep(10), _.timeout(100)]) | ||
|
||
vi.advanceTimersByTime(100) | ||
|
||
await expect(promise).resolves.toBeUndefined() | ||
}) | ||
|
||
test('rejects with timeout when it finishes before sleep', async () => { | ||
const promise = Promise.race([_.sleep(100), _.timeout(10)]) | ||
|
||
vi.advanceTimersByTime(100) | ||
|
||
await expect(promise).rejects.toThrow() | ||
}) | ||
}) | ||
}) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
timeout.test.ts
is misspelled astimout.test.ts
🙃